2013-05-10 212 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.. 
    } 
相關問題