![](/img/trans.png)
[英]IntelliJ IDEA File FileNotFoundException, directory and file exists?
[英]IntelliJ “FileNotFoundException”, File Exists
我的目標是閱讀IntelliJ上的文本文件。 但是,當我運行我的代碼時,我收到“FileNotFoundException”消息。 我的檔案存在。 我進行了三重檢查以確保路徑正確。 我已經搜索了Stack Overflow尋找答案,閱讀我遇到的每個問題,但沒有人提出具體的解決方案。
這是我的代碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LetterGrader {
public static void main(String[] args) {
String curDir = new File(".").getAbsolutePath();
System.out.println("Current sys dir: " + curDir);
try {
File inputData = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(inputData));
} catch (IOException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
}
這是出現的錯誤消息。
File not found
java.io.FileNotFoundException: input.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.io.FileReader.<init>(FileReader.java:72)
at LetterGrader.main(LetterGrader.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 0
任何幫助將不勝感激! 當我找到解決方案時,我也會回復。
[UPDATE]
我通過將“input.txt”文件或src文件夾移動到主項目的文件夾中解決了這個問題。
我還使用Scanner而不是BufferedReader。
我的最終代碼有效:
try {
Scanner diskScanner = new Scanner(new File("input.txt"));
while (diskScanner.hasNextLine()) {
System.out.println(diskScanner.nextLine());
}
diskScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
您可以嘗試首先打印文件的絕對路徑
System.out.println(new File("input.txt").getAbsolutePath());
然后,由於您使用的是IntelliJ,您可以在IDE中打開終端並嘗試從那里打開該文件。 例如:
cat /Users/antonpp/Documents/Projects/testapp/input.txt
因此,您將完全確定該文件存在且位於正確的位置。
問題是由於工作目錄的不同,即源代碼所在的目錄和IntelliJ
的當前工作目錄不同。 通常,工作目錄是項目的主目錄。 因此,要么將文件放在該目錄中,要么使用“ Edit Configurations...
選項。 選擇“ Edit Configurations...
,請選中“ Working directory
”選項並相應地進行更改。
哦,我也有一些問題。 因此,請嘗試Edit Configurations
。 您可以在運行 - >編輯配置中找到它。然后編輯Working directory
到您的文件所在的位置。 順便說一句,您可以將其編輯到基目錄並在代碼中添加路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.