Java 如何读取文本文件中除最后一行以外的全部文本?
我已经写了一个代码来打印文本文件中的全部文本,但我不知道如何使它能够读取除最后一行之外的全部文本 守则:Java 如何读取文本文件中除最后一行以外的全部文本?,java,inputstream,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 te
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();
}
}
}
}
我想上面的代码可以读取文本,除了最后一行
感谢您的帮助无法编写您的程序,使其不读取最后一行;程序必须先读取最后一行,然后再尝试另一次读取,才能判断该行是最后一行。您需要的是一个“前瞻”算法,它类似于以下伪代码:
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
}
}
最简单的方法可能是每次打印前一行:
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
为什么要在循环中读取一行两次?请,这不是我的问题。。我最简单的问题是:除了最后一段,有没有办法阅读全文line@user2976643:那么你需要澄清你的问题。这将打印出文件的最后一行以外的所有内容,我认为这是您试图实现的。如果你真的想避免读最后一行,那么怎么知道你是否读到了最后一行呢?