Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

LineNumberReader - efficient reading of specific lines from text files

922333Mar 7 2012 — edited Mar 7 2012
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;
		}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 4 2012
Added on Mar 7 2012
5 comments
1,072 views