views:

209

answers:

4

Hello. I'm having some problems with the FileReader class.

How do I specify an offset in the lines it goes through, and how do I tell it when to stop? Let's say I want it to go through each line in a .txt file, but only lines 100-200 and then stop?

How would I do this? Right now I'm using ReadLine() but I don't think there's a way to specify offset with that.

Any fast help is VERY appreciated. Thanks.

+2  A: 

Read all the lines but use another variable to count which line you are on. Call continue if you are on a line that you don't want to process (say, before the 100th line) and break when you will not want to process any more lines (after the 200th line).

mobrule
Of course. Thanks.
Cris Carter
+3  A: 
  1. You can't. FileReader reads a character at a time or a line at a time. Obviously you can write your own code extending or wrapping it to skip to the unneeded lines.

  2. An aside: Be CAREFUL using FileReader or FileWriter - they use the default LOCALE character set. If you want to force a character set use OutputStreamWriter or InputStreamReader. Example

Writer w = new FileWriter(file) can be replaced by Writer w = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); <=== see how I can set the character set.

  1. An alternative: If you have FIXED-WIDTH text, then look at RandomAccessFile which lets you seek to any position. This doesn't help you much unless you have fixed width text or an index to skip to a line. But it is handy :)
MJB
+1  A: 

There is not a way to tell the reader to only read certain lines, you can just use a counter to do it.

try { 
    BufferedReader in = new BufferedReader(new FileReader("infilename")); 
    String str; 
    int lineNumber = 0;

    while ((str = in.readLine()) != null) { 
        lineNumber++;

        if (lineNumber >= 100 && lineNumber <= 200) {
            System.out.println("Line " + lineNumber + ": " + str);
        }
    } 

    in.close(); 
} catch (IOException e) { } 
Ascalonian
A: 
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
for(int i=0;i<100;i++,in.readLine()){}
String line101 = in.readLine();
Randyaa