2013-05-10 137 views
0

所以我想用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

此代码不应忽略任何现有的行,无论是否为空。你确定有一条线吗?你可以用'wc -l'来验证,并将它与你在循环中实现的计数器进行比较? – jlordo 2013-05-10 07:45:35

+0

完成后请关闭流'in'。 – xagyg 2013-05-10 08:31:12

+0

可能的重复http://stackoverflow.com/questions/9922859/bufferedreader-readline-issue-detecting-end-of-file-and-empty-return-lines – xagyg 2013-05-10 08:34:20

回答

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