我在 eclipse 中有一个 java 项目,并且有一个从文件读取信息的方法。当我对该方法进行 JUnit 测试时,它无法找到该文件,即使它位于我的工作树中并且我使用了正确的类路径声明。
读取文件的方法:
public static ArrayList<Issue> readIssuesFromFile(String filename) {
ArrayList<Issue> issues = new ArrayList<Issue>();
try {
Scanner sc = new Scanner(new FileInputStream(filename));
String text = "";
while(sc.hasNextLine()) {
text+= sc.nextLine();
text+= "\n";
}
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
JUnit 测试:
public void testReadIssueFromFile() {
String test = "test-files/valid_file.txt";
try {
ArrayList<Issue> issues = IssueReader.readIssuesFromFile(testFile);
assertEquals(issues.get(0).getIssueId(), 0);
} catch (Exception e) {
fail(e.getMessage());
}
}
工作树:
->Project
->src
->.java file containing method
->test
->JUnit test file
->test-files
->txt file
最佳答案
根据你的工作树,我认为你的路径应该是:
../test-files/valid_file.txt
您使用的路径(test-files/valid_file.txt
)意味着在 JUnit 文件的文件夹中搜索名为 test-files
的文件夹,并在该文件夹内搜索名为 valid_file.txt
的文件。
根据您的工作树,情况并非如此。因此,您需要 ..
移动到上一级,您可以在其中找到文件夹 test-files
。
如果它仍然不起作用,也许可以尝试通过打印您使用过的路径来调试您的程序,如下所示:
try {
/* Here you can replace the period with another path like "test-files/valid_file.txt"
* to see the absolute path of it
*/
System.out.print(new java.io.File( "." ).getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
关于java - 当我的文件确实存在时,出现文件未找到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560162/