Search Unity

Can I read and write text files using Javascript?

Discussion in 'Scripting' started by Daniel_Brauer, May 24, 2007.

  1. Daniel_Brauer

    Daniel_Brauer

    Unity Technologies

    Joined:
    Aug 11, 2006
    Posts:
    3,355
    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?
     
  2. hsparra

    hsparra

    Joined:
    Jul 12, 2005
    Posts:
    750
    How about something like this?
    Code (csharp):
    1.  
    2. import System.IO;
    3. var filePath = "/Users/ResetOfDirectoryPath/testWrite.txt";
    4.  
    5. function Update() {
    6.     if (Input.GetKeyDown("r")) {
    7.         WriteFile(filePath);
    8.     }
    9.     if (Input.GetKeyDown("f")) {
    10.         ReadFile(filePath);
    11.     }
    12. }
    13.  
    14. function WriteFile(filepathIncludingFileName : String)
    15. {
    16.     var sw : StreamWriter = new StreamWriter(filepathIncludingFileName);
    17.     sw.WriteLine("Line to write");
    18.     sw.WriteLine("Another Line");
    19.     sw.Flush();
    20.     sw.Close();
    21. }
    22.  
    23. function ReadFile(filepathIncludingFileName : String) {
    24.     sr = new File.OpenText(filepathIncludingFileName);
    25.  
    26.     input = "";
    27.     while (true) {
    28.         input = sr.ReadLine();
    29.         if (input == null) { break; }
    30.         Debug.Log("line="+input);
    31.     }
    32.     sr.Close();
    33. }
    34.  
    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.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Also, here's a quick translation of those C# examples to JS from that .NET documentation:

    Read:
    Code (csharp):
    1. import System.IO;
    2.  
    3. function Start () {
    4.     try {
    5.         // Create an instance of StreamReader to read from a file.
    6.         sr = new StreamReader("TestFile.txt");
    7.         // Read and display lines from the file until the end of the file is reached.
    8.         line = sr.ReadLine();
    9.         while (line != null) {
    10.             print(line);
    11.             line = sr.ReadLine();
    12.         }
    13.         sr.Close();
    14.     }
    15.     catch (e) {
    16.         // Let the user know what went wrong.
    17.         print("The file could not be read:");
    18.         print(e.Message);
    19.     }
    20. }
    Write:
    Code (csharp):
    1. import System.IO;
    2. import System;  // Used for getting the date
    3.  
    4. function Start () {
    5.     // Create an instance of StreamWriter to write text to a file.
    6.     sw = new StreamWriter("TestFile.txt");
    7.     // Add some text to the file.
    8.     sw.Write("This is the ");
    9.     sw.WriteLine("header for the file.");
    10.     sw.WriteLine("-------------------");
    11.     // Arbitrary objects can also be written to the file.
    12.     sw.Write("The date is: ");
    13.     sw.WriteLine(DateTime.Now);
    14.     sw.Close();
    15. }
    By default the file goes into the base folder of your current project.

    --Eric
     
  4. Daniel_Brauer

    Daniel_Brauer

    Unity Technologies

    Joined:
    Aug 11, 2006
    Posts:
    3,355
    This is great! Thanks very much.
     
  5. Maker16

    Maker16

    Joined:
    Mar 4, 2009
    Posts:
    779
    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?
     
  6. janstec

    janstec

    Joined:
    Jun 23, 2010
    Posts:
    13
    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!
     
  7. Chris-Sinclair

    Chris-Sinclair

    Joined:
    Jun 14, 2010
    Posts:
    1,326
    Are you building a standalone desktop game or one for the browser web player?
     
  8. janstec

    janstec

    Joined:
    Jun 23, 2010
    Posts:
    13
    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 :D
     
  9. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    is it possible to write in 'textfield' and then save as a txt or jpg?
     
  10. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    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.
     
  11. MohammadAburumman

    MohammadAburumman

    Joined:
    Feb 23, 2012
    Posts:
    1
    I can Read One word from Text file i choose it in inspector as Text Assets and save this word in string
     
  12. achingupta87

    achingupta87

    Joined:
    Apr 9, 2012
    Posts:
    144
    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
     
  13. RingOfStorms

    RingOfStorms

    Joined:
    Oct 23, 2010
    Posts:
    584
    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.
     
  14. kresnik

    kresnik

    Joined:
    Sep 28, 2012
    Posts:
    7
    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
     
    Last edited: Nov 21, 2012
  15. basil

    basil

    Joined:
    Dec 13, 2012
    Posts:
    9
    Hi, I am buliding a game for mobile. is there any alternative to find the path dynamically?
     
  16. UnityCoder

    UnityCoder

    Joined:
    Dec 8, 2011
    Posts:
    534
    Application.dataPath give you dynamic path of application.
     
  17. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    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:
    Code (csharp):
    1. var numStr : String = line.Substring(line.IndexOf("=") + 1);
    2. var delim : String[] = { "," };
    3. var numParts : String[] = numStr.Split(delim, StringSplitOptions.RemoveEmptyEntries);
    4. var xCoord : float = parseFloat(numParts[0].Trim());
    5. ...
     
  18. Marcelomacm

    Marcelomacm

    Joined:
    May 21, 2013
    Posts:
    3
    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
     
  19. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Look in the File classes. Particularly AppendText in this case.

    --Eric
     
  20. Caliber-Mengsk

    Caliber-Mengsk

    Joined:
    Mar 24, 2010
    Posts:
    689
    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.
     
  21. Marcelomacm

    Marcelomacm

    Joined:
    May 21, 2013
    Posts:
    3
    ...
    sw = new StreamWriter("Roupeiro.txt", true);
    sw.Write("Item escolhido: ");
    sw.WriteLine(item.name);
    sw.Write("Tempo: ");
    sw.WriteLine(Time.time);
    sw.WriteLine("------------------------------------");
    sw.Close();
    ...

    if i put "true", it will not overwrite the file!!
     
  22. unity fly

    unity fly

    Joined:
    Jul 26, 2013
    Posts:
    2
    hi,

    i have a xml file which is downloaded from the external server using url and saved in a SD card.

    I have to Assign that XML file to a variable of GameObject.

    How it is possible, can u suggest me?






     
  23. rahulreddyv

    rahulreddyv

    Joined:
    Mar 11, 2014
    Posts:
    2
    How to erase data from these files?
     
  24. amthecoolest

    amthecoolest

    Joined:
    Aug 20, 2014
    Posts:
    1
    so trying to figure out something, how do I work out the actual js script from the final design? is it something that I click onto or something that I have to write down on paper? want to know how to do this! HELP SOMEONE