Wanna skip exact number lines while reading a file file
Hi all,
I would like to skip exact number of lines while reading a text file.
Let's say I wanna read this text file starting from line no N.
And so I need to skip from fist line to N-1th line.
Does anyone give me a way to do?
Pls with a sample code if possible coz I am not familiar much to java. :P
[338 byte] By [
Candy] at [2007-11-26 12:17:45]

# 2
BufferedReader in = new BufferedReader(new FileReader(new File("yourfile.txt")));
String line = null;
int count = 0;
int startAtLineNo = ...; // 0-based
while ((line = in.readLine()) != null) {
if (count >= startAtLineNo) {
/* do stuff */
}
// else ignore
count++;
}
# 3
If the file's records are fixed length, you can jump directly to the desired line using the RandomAccessFile class; otherwise, you will need to read the file from the beginning and count the lines until you get to the one you want.
jbish at 2007-7-7 14:55:42 >

# 4
LineNumberReader class keeps track on line number for you. Sample that skip arg3 lines while copy arg1 file to arg2. Just sample no check, no cleanup.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class Main {
public static void main(String... args) throws Exception {
if (args.length != 3)
throw new IllegalArgumentException("Arguments: infile outfile line_from");
LineNumberReader reader = new LineNumberReader(
new FileReader(new File(args[0])) );
BufferedWriter writer = new BufferedWriter(
new FileWriter(new File(args[1])) );
int readFrom = Integer.valueOf(args[2]);
// skip first lines
while(reader.getLineNumber() < readFrom) {
if (reader.readLine() == null)
throw new IllegalArgumentException("Too few lines");
}
// write tail
String line = null;
while((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
writer.flush();
}
}