Java – how to use the Detect the first and last lines in readline()?

I read each line of the file in the following way

BufferedReader in = new BufferedReader(new FileReader(inFile));

while (null != (line = in.readLine())) {


}

I want to do some validation separately on the first and last lines Did you check whether it is the first and last line in the while loop

while (null != (line = in.readLine())) {    

    if(firstlineoffile) {
    }

    else if (lastlineoffile) {
    }

    else
    {
    }

}

Solution

Cool question I played a circle, this is an sscce, just copy 'n' paste 'n' run it

package com.stackoverflow.q2292917;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class Test {

    public static void main(String... args) throws IOException {
        // Create test file.
        File file = new File("/test.txt");
        PrintWriter writer = new PrintWriter(file);
        writer.println("line 1");
        writer.println("line 2");
        writer.println("line 3");
        writer.println("line 4");
        writer.println("line 5");
        writer.close();

        // Read test file.
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String next,line = reader.readLine();
            for (boolean first = true,last = (line == null); !last; first = false,line = next) {
                last = ((next = reader.readLine()) == null);

                if (first) {
                    System.out.println("first line: " + line);
                } else if (last) {
                    System.out.println("last line: " + line);
                } else {
                    System.out.println("normal line: " + line);
                }
            }
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException logorIgnore) {}
        }

        // Delete test file.
        file.delete();
    }

}

Output:

first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5

However, I question the readability and interpretability of beginners...;)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>