I looked at the .NET documentation for the File class, but none of their example code is in JS. How do I read and write text files using Javascript?
How about something like this?
import System.IO;
var filePath = "/Users/ResetOfDirectoryPath/testWrite.txt";
function Update() {
if (Input.GetKeyDown("r")) {
WriteFile(filePath);
}
if (Input.GetKeyDown("f")) {
ReadFile(filePath);
}
}
function WriteFile(filepathIncludingFileName : String)
{
var sw : StreamWriter = new StreamWriter(filepathIncludingFileName);
sw.WriteLine("Line to write");
sw.WriteLine("Another Line");
sw.Flush();
sw.Close();
}
function ReadFile(filepathIncludingFileName : String) {
sr = new File.OpenText(filepathIncludingFileName);
input = "";
while (true) {
input = sr.ReadLine();
if (input == null) { break; }
Debug.Log("line="+input);
}
sr.Close();
}
As this currently stands, it will simply overwrite the file if it already exists. Of course you would probably want to enhance this to handle multiple calls, etc.
Also, here’s a quick translation of those C# examples to JS from that .NET documentation:
Read:
import System.IO;
function Start () {
try {
// Create an instance of StreamReader to read from a file.
sr = new StreamReader("TestFile.txt");
// Read and display lines from the file until the end of the file is reached.
line = sr.ReadLine();
while (line != null) {
print(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (e) {
// Let the user know what went wrong.
print("The file could not be read:");
print(e.Message);
}
}
Write:
import System.IO;
import System; // Used for getting the date
function Start () {
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
By default the file goes into the base folder of your current project.
–Eric
This is great! Thanks very much.
How would I read for characters instead of lines? For example, if I wanted to save the position of something to a text file, writing it is easy enough, but when I want to load that position, how do I tell it to set the position to the first value, the second position for the secod value, the third position for the thid value as they are read in from the file?
It worked for me when using the editor. When I actually create a build it does not generate the file.
Any ideas on why this could be happening?
Thanks!
Are you building a standalone desktop game or one for the browser web player?
Desktop.
I solved my problem using PlayerPrefs, as I was just trying to store the value of a COM port for later use. That being said, I would still like to know how to do it
is it possible to write in ‘textfield’ and then save as a txt or jpg?
The example above writes to a text file. If you can generate the data in the correct format then you will be able to create a JPEG file, but there is nothing in the Unity API to create JPEG data. However, there is Texture2D.EncodeToPNG which might be a viable alternative.
I can Read One word from Text file i choose it in inspector as Text Assets and save this word in string
Hello Eric
I wants to use this code in our project but file is not found it gives exceptions Could not find file “C:\Users\achin_gupta\Documents\sampledatabase\sample.txt”. I put the .txt file in the Resources folder in project.
please help
Thanks
After reading this, I would recommend you learn how to use XML, it is not much harder than a text file - and instead of cluttering your entire registry with player prefs, you can encrypt and store more data in a much easier way with xml databases.
is it possible if i write in the update function?
i want to record the number of fps, so in each frame, the system will write the fps in txt/xml(per frame writing)
i’m using http://wiki.unity3d.com/index.php?title=FramesPerSecond to count the fps
plus the final health value of each player (there is more than one player), so when application quit, txt will appear and show the result of fps on each frame (or if you can show the average yield is very helpful) and health value of each player at the application quit
thanks
Hi, I am buliding a game for mobile. is there any alternative to find the path dynamically?
Application.dataPath give you dynamic path of application.
Do you mean something like this?
Position = 35.3, 47.2, 31.8
String.Split would probably be what you want here. For example, to parse that particular format:
var numStr : String = line.Substring(line.IndexOf("=") + 1);
var delim : String[] = { "," };
var numParts : String[] = numStr.Split(delim, StringSplitOptions.RemoveEmptyEntries);
var xCoord : float = parseFloat(numParts[0].Trim());
...
Hi, I have this code:
…
sw = new StreamWriter(“Roupeiro_camisa.txt”);
sw.Write("Item escolhido: ");
sw.WriteLine(item.name);
sw.Write("Tempo: ");
sw.WriteLine(Time.time);
sw.Close();
…
this, write to new text file always.
But i want that insted of write to a new file, this add infomation to alredy existing file.
Help please
Look in the File classes. Particularly AppendText in this case.
–Eric
You should also be able to use System.IO.File.WriteAllText and System.IO.File.ReadAllText. Those both just use input/output a string. Don’t know if this would work with android/ios devices, but should work on standalone at least.
To use those though, you can’t be using the .net subset, and it has to be changed in the player settings to use the full .net framework. It adds on a few megabytes to the file to do that.
I’d test it on android, but meh. This is by far the easiest to understand method of reading and writing files though.
As you found out though, playerprefs is fairly simple to use and for many cases is fine, but if you ever need it, now you know a very simple way to read/write files.