user2976643
user2976643

Reputation: 35

How to read whole the text in text file except last line?

I have write a code to print the whole text in text file but i couldn't know how to enable it to read the whole text except last line

The Code :

public class Files {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    // -- This Code is to print the whole text in text file except the last line >>>
    BufferedReader br = null;
    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("FileToPrint.txt"));
        String s = br.readLine();
        while (true) {
            if ((sCurrentLine = br.readLine()) != null) {
                System.out.println(s);
                s = sCurrentLine;
            }
            if ((sCurrentLine = br.readLine()) != null) {
                System.out.println(s);
                s = sCurrentLine;
            } else {
                break;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}

}

i want the code above can read the text except last line ,,,

thanks for help

Upvotes: 1

Views: 1981

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500145

The simplest approach is probably to print the previous line each time:

String previousLine = null;
String line;
while ((line = reader.readLine()) != null) {
    if (previousLine != null) {
        System.out.println(previousLine);
    }
    previousLine = line;
}

I'd also suggest avoiding catching exceptions if you're just going to print them out and then continue - you'd be better using a try-with-resources statement to close the reader (if you're using Java 7) and declare that your method throws IOException.

Upvotes: 2

ajb
ajb

Reputation: 31689

There's no way to write your program so that it doesn't read the last line; the program has to read the last line and then try another read before it can tell that the line is the last line. What you need is a "lookahead" algorithm, which will look something like this pseudo-code:

read a line into "s"
loop {
    read a line into "nextS"
    if there is no "nextS", then "s" is the last line, so we break out of the
        loop without printing it
    else {
        print s
        s = nextS
    }
}

Upvotes: 0

Related Questions