简体   繁体   English

如何读取文本文件中除最后一行以外的全部文本?

[英]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 感谢帮助

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 . 我还建议您避免将异常打印出来,然后继续执行-最好使用try-with-resources语句关闭阅读器(如果您使用的是Java 7)并声明您的方法将引发IOException

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM