- Home /
How to read particular line from *.txt file?
How can I get a string which is for example in 4th line of a text file? Here's the code I'm using to read/write/edit file:
import System.IO;
var filePath = "/Users/testWrite.txt";
function Update(){
if (Input.GetKeyDown("c")) {
WriteFile(filePath);
}
if (Input.GetKeyDown("w")) {
AddToFile(filePath);
}
if (Input.GetKeyDown("r")) {
ReadFile(filePath);
}
}
function WriteFile(filepathIncludingFileName : String){
var sw : StreamWriter = new StreamWriter("testFile.txt");
sw.WriteLine("Line to write");
sw.WriteLine("Another Line");
sw.Flush();
sw.Close();
}
function AddToFile(filepathIncludingFileName : String){
sr = File.AppendText("testFile.txt");
sr.WriteLine("Added ");
sr.Write("Another Line");
sr.Flush();
sr.Close();
}
function ReadFile(filepathIncludingFileName : String) {
sr = new File.OpenText("testFile.txt");
input = "";
while (true) {
input = sr.ReadLine();
if (input == null) { break; }
Debug.Log("line="+input);
}
sr.Close();
}
Answer by whydoidoit · Jun 23, 2012 at 03:59 PM
You could read the whole file into a list and then you could access any line you like: import System.Collections.Generic; import System.Linq;
var fileLines : List.<String>;
function ReadFile() {
var sr = File.OpenText("whatever.txt");
fileLines = sr.ReadToEnd().Split("\n"[0]).ToList();
sr.Close();
}
Now you have a list of lines that you can insert into, get a specific line from - whatever. If you want to write them back out you can just do:
var wholeFileText = String.Join("\n", fileLines.ToArray());
Can you make a C# answer also plz... I'm stuck in the same problem but im using C#...
The easiest way to read lines of text into a list is probably:
List<string> fileLines = new List<string>(System.IO.File.ReadAllLines("FILEPATH"));
To write them back (overwriting the old file contents):
System.IO.File.WriteAllLines("FILEPATH", fileLines.ToArray());
"FILEPATH" would be replaced with whatever the path to your file is.
This is the easiest way as far as I know, but it's not the best performance wise. There's a lot of converting from array to list and back.
Your answer
Follow this Question
Related Questions
Accessing local system ( File Browser ) 2 Answers
Confused about intermediate string reading. 1 Answer
Write and read text files with c# 1 Answer
How do I read read from and write to a text file? 2 Answers
Why is reading some text files with JS so darn slow?! (title changed to reflect answers) 1 Answer