Share on Google+Share on Google+

Java file line reader

Advertisement
In this section, you will learn how to read a particular line from file.

Java file line reader

In this section, you will learn how to read a particular line from file.

Sometimes you want to read a particular line from the file but you have to read the whole file for this process. So in order to remove this lengthy and unnecessary coding, this section will really helpful for you.

You can see in the given example, we have created an object of FileReader class and parse the file path. Through the code, we want to read the line 3 of the file, so we have created a for loop which iterates the lines 1-10 of the text file. When loop reaches the third line, the br.readLine() method of BufferedReader class read that particular line and display it on the console.

Here is the file.txt:

Hello World
All glitters are not gold.
Truth is better than facts.
Dreams are the touchstones of the nature.

Here is the code:

import java.io.*;

public class FileReadParticularLine {
	public static void main(String[] args) {
		String line = "";
		int lineNo;
		try {
			FileReader fr = new FileReader("C:/file.txt");
			BufferedReader br = new BufferedReader(fr);
			for (lineNo = 1; lineNo < 10; lineNo++) {
				if (lineNo == 3) {
					line = br.readLine();
				} else
					br.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Line: " + line);
	}
}

Through the above code, you can read any line of any file.

Output:

Line: All glitters are not gold.

Advertisements

Posted on: April 28, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.