我目前正在嘗試編寫一個程序,它將逐行讀入文件並將每行添加到arrayList中。我的其他函數應該對來自該緩衝區的項目進行排序,然後將它們寫入文本文件。但是,即使我的文件位於src目錄中,以及具有我的.class文件的目錄中,我仍然不斷收到FileNotFoundException。我的代碼如下總是收到FileNotFoundException,即使使用SRC文件夾中的文件
public static ArrayList<String> readDictionary(String filename,
ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Scanner fileIn = new Scanner(f);
//Scanner fileIn = new Scanner(new File(filename));
boolean add = true;
while (fileIn.hasNextLine() == true) {
for (String s : buffer) {
if (fileIn.nextLine().equals(s)) {
add = false;
}
}
if (add == true) {
buffer.add(fileIn.nextLine());
}
add = true;
}
fileIn.close();
return buffer;
}
public static void writeDictionary(String filename, ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Collections.sort(buffer, String.CASE_INSENSITIVE_ORDER);
Path file = Paths.get(filename);
Files.write(file, buffer);
}
public static void main(String[] args) throws IOException, FileNotFoundException{
ArrayList<String> buffer = new ArrayList<>();
readDictionary("inputtest.txt", buffer);
}
Exception in thread "main" java.io.FileNotFoundException: inputtest.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at UltimateDictionary.readDictionary(UltimateDictionary.java:18)
at UltimateDictionary.main(UltimateDictionary.java:46)
我通過設置文件名等於「inputtest.txt」測試這個程序,而該文件正坐在與java文件我的src目錄,但它仍然拋出的錯誤。另外,我怎樣才能關閉這些文件? f.close()給我一個錯誤。
你能否提供詳細的錯誤信息? – Fabien
我在錯誤消息中編輯了以及用於測試它的主要方法。當文本文件位於目錄中時,我看不到如何得到此錯誤。 –
提供絕對路徑怎麼樣?它可能來自應用程序從另一個工作目錄啓動的事實。 – Fabien