如何读取除最后一行之外的文本文件中的整个文本?

时间:2013-12-16 17:09:26

标签: java inputstream

我已经编写了一个代码来打印文本文件中的整个文本,但我不知道如何启用它来读取除最后一行之外的整个文本

守则:

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();
        }
    }


}

}

我希望上面的代码可以读取除最后一行以外的文字,

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

最简单的方法可能是每次打印之前的行:

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

我还建议避免捕获异常,如果你只是打印它们然后继续 - 你最好使用try-with-resources语句关闭阅读器(如果你使用的是Java 7)并声明您的方法抛出IOException

答案 1 :(得分:0)

没有办法编写你的程序,因此它不会读取最后一行;程序必须读取最后一行,然后尝试另一次读取才能判断该行是最后一行。你需要的是一个“先行”算法,它看起来像这个伪代码:

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
    }
}
相关问题