File IO

From ETC Public Wiki
Jump to: navigation, search

Finding Paths

 Debug.Log(Application.persistentDataPath);  // text file in users app data
 Debug.Log(Application.dataPath);            // text file in games data folder

CSV file

A csv file is a text file where every field is seperated by a "," Create and read them in EXCEL

Example data file:

 Red Shark Alpha,1234
 Green Bear Beta,4321
 Blue Wolf Gamma,2222

Example code:

 import System.IO;
 
 private var fileTeams : String;
 private var teamsTable = new Array(); 
 
 function Start () {
 	// use Application.persistentDataPath later
 	fileTeams = Application.dataPath + "/teams.csv";
 }
   
 function ReadFile (name : String) {
 	// open the supplied file for reading
 	// read the file and return an array of strings 
 	var sr : StreamReader = File.OpenText(name);
 	var data = new Array();
 	var line = sr.ReadLine();
        while (line != null) {
   	    //Debug.Log(line);
   	    data.Add(line);
            line = sr.ReadLine();
        }
        sr.Close();
        return data;
 	
 }
 
 function WriteFile ( name : String, addOnto : boolean, data : Array) {
 	// open the file for writing or appending based on addOnto
 	// write the contents of data array to the file
 	var sw : StreamWriter; 
 	if (addOnto) {  sw  = File.AppendText(name); }
 	else {  sw  = File.CreateText(name); }
 	
 	for ( var line : String in data ) {
 		sw.WriteLine(line);
 	} 
 	sw.Close();
 }
 
 function GetTeams ( ) {
 	// read in the teams data and return a 2D array of team names and passwords
 	var names = new Array();
 	var pass = new Array();
 	var table  = new Array();
 	var file = new Array();
 	file = ReadFile( fileTeams );  // returns an array of strings
 	for (var line : String in file) {
 		var temp = line.Split(","[0]);  // seperate the string into elements based on ","s
 		names.Add(temp[0]);
 		pass.Add(temp[1]); 
 	}
 	// build the table => table[0][team#] = team name, table[1][team#] = team pass
 	table.Add(names);
 	table.Add(pass);
        
        // test the table - stored table[c][r]
 	for (var i = 0; i < table[0].length; i ++) { Debug.Log( table[0][i] + " " + table[1][i] ); }
 
 	return table;
 }