所以我试图用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();}
}
答案 0 :(得分:1)
首先使用扫描仪类......因为它们更易于使用....然后将每行存储在一个列表中,然后获取最后一行......这是代码:
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..
}