我正在做一個關於讀取文件的示例。我把一個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();
'dataInputStream'超出範圍,所以你的代碼不能引用它。發佈堆棧跟蹤以獲取更多幫助。該文件可能丟失。 – 2013-04-11 18:45:34
在try塊外聲明DataInputStream,然後您將能夠在底部關閉它。 – 2013-04-11 18:48:14
該文件很可能嵌入在應用程序jar中,您可能需要使用getClass()。getResource(「myfile.txt」)而不是 – MadProgrammer 2013-04-11 18:50:15