所以我正在尝试用 Java 读取文件。它工作得很好,除非最后一行是空的,在这种情况下它会被忽略;但我也需要阅读这个空行。
这是我的代码:
try
{
BufferedReader in = new BufferedReader(new FileReader("filename.txt"));
String Line;
while((Line = in.readLine()) != null)
{
System.out.println("L| " + Line);
}
}
catch(Exception e){e.printStackTrace();}
}
最佳答案
首先使用扫描仪类......因为它们更容易使用......然后将每一行存储在列表中,然后获取最后一行......这是代码:
public void readLast()throws IOException{
FileReader file=new FileReader("E:\\Testing.txt"); //address of the file
List<String> Lines=new ArrayList<>(); //to store all lines
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){ //checking for the presence of next Line
Lines.add(sc.nextLine()); //reading and storing all lines
}
sc.close(); //close the scanner
System.out.print(Lines.get(Lines.size()-1)); //displaying last one..
}
关于java - 从文件中读取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16477388/