2013-04-11 78 views
0

我正在做一個關於讀取文件的示例。我把一個txt文件放到項目文件夾中,並寫下了這段代碼,但是我得到了異常FileNotFound,並且當我試圖關閉時dataInputStream我收到了編譯錯誤(註釋掉了行)。我想我搞砸了一切從文件中讀取錯誤

String str=null; 
    try { 
     FileInputStream fileInputStream=new FileInputStream("myfile.txt"); 
     DataInputStream dataInputStream=new DataInputStream(fileInputStream); 
     BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(dataInputStream)); 
     str=bufferedReader.readLine(); 

     } catch (Exception e) { 
      System.out.println(e.getMessage()); 
     } 

     System.out.println(str); 
     //dataInputStream.close(); 
+2

'dataInputStream'超出範圍,所以你的代碼不能引用它。發佈堆棧跟蹤以獲取更多幫助。該文件可能丟失。 – 2013-04-11 18:45:34

+0

在try塊外聲明DataInputStream,然後您將能夠在底部關閉它。 – 2013-04-11 18:48:14

+0

該文件很可能嵌入在應用程序jar中,您可能需要使用getClass()。getResource(「myfile.txt」)而不是 – MadProgrammer 2013-04-11 18:50:15

回答

2

Java是真的挑剔關於相對路徑,所以`「myfile.txt的」可能應該生活在何處項目正在建設中。

至於關閉dataInputStream,它不在範圍內。在你的try塊之外聲明它。無論如何,我建議將實際的close()調用放在finally塊中,以確保它始終完成(如果引用不爲空)。

0

我同意吉列爾莫

myfile.txt需要在你的類路徑。

如果您在命令行中運行此代碼,它應位於與此代碼執行相同的文件夾或相同的包中。

作爲DataInput中的流是超出範圍

+0

如果文件位於相同的包(或類路徑)內,OP應該使用getClass()。getResource(...),它將使用類路徑作爲執行搜索的上下文(相對於它) – MadProgrammer 2013-04-11 19:05:21

+0

謝謝朋友 – digrev 2013-04-11 19:26:58

0

bufferedReader.close()必須在你關閉此操作結束使用..