I'm looking for efficient ways to read specific lines from text files as text. I'll be reading from a number of large text files, so I'd prefer to find faster ways of doing it.
After getting LineReader to work by trial and error, I need to ask some dumb questions.
The first is this; when should I convert it to a String?
Below are two alternatives. Are they similar, or is one more efficient than the other in terms of CPU/RAM ?
The first appears (?) to convert every line to a string, but it only "keeps" the last result. Perhaps you can correct me, but this seems inefficient (because it's got to keep dumping strings until it gets to the one it wants).
public String getLineFromFile(String fileName, int lineNumber){
LineNumberReader lnr = new LineNumberReader(getFileReader(fileName));
String s = null;
while (lnr.getLineNumber() < lineNumber){
try {
s = lnr.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}
The second only does the String thing when it arrives at the line that's required
public String getLineFromFile(String fileName, int lineNumber){
LineNumberReader lnr = new LineNumberReader(getFileReader(fileName));
while (lnr.getLineNumber() < lineNumber - 1);
String s = null;
try {
s = lnr.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
Both methods use this...
public FileReader getFileReader(String fileName){
FileReader f = null;
try {
f = new FileReader(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return f;
}