Home Tutorial Java Core Read file from the Nth line

 
 

Share on Google+Share on Google+
Read file from the Nth line
Posted on: January 15, 2011 at 12:00 AM
Advertisement
This section illustrates you how to read a file content from a particular line till end.

Read file from the Nth line

Java provides several classes and methods to manipulate file. A file reading, is a common operation. Usually a file is to be read from top to bottom but here we are going  to read a file content from a particular line till end.

Here is the code:

import java.io.*;
import java.util.*;

public class ReadNthLineToEnd {
	public static void main(String[] args) {
		StringBuffer buffer = new StringBuffer();
		String line = "";
		int lineNo;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Line Number: ");
		int no = input.nextInt();
		try {
			LineNumberReader ln = new LineNumberReader(new FileReader(
					"C:/hello.txt"));
			int count = 0;
			while (ln.readLine() != null) {
				count++;
			}
			ln.close();
			FileReader fr = new FileReader("C:/hello.txt");
			BufferedReader br = new BufferedReader(fr);
			for (lineNo = 1; lineNo <= count; lineNo++) {
				if (lineNo == no) {
					for (lineNo = no; lineNo <= count; lineNo++) {
						buffer.append(br.readLine());
						buffer.append("\n");
					}
				} else
					br.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(buffer.toString());
	}
}
Advertisement

Related Tags for Read file from the Nth line:


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.

Posted on: January 15, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com