Read Specific Line from file Using Java

In this section,you will learn how to read a specific line from the text file.

 
 

Share on Google+Share on Google+

Read Specific Line from file Using Java

Ads

In this section,you will learn how to read a specific line from the text file.

Read Specific Line from file Using Java

Here we are going to read a specific line from the text file. For this we have created a for loop to read lines 1 to 10 from the text file. If the loop reached fifth line, the br.readLine() method of BufferedReader class read that particular line and display it on the console.

Here is the code :

import java.io.*;

public class ReadSpecificLine {

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

Advertisements

Posted on: October 30, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles