gpt4 book ai didi

java - maven:尝试使用 Intellij 从资源打开文件或使用带有 jar 的 java 命令时出现 java.io.FileNotFoundException

转载 作者:行者123 更新时间:2023-11-30 02:54:43 25 4
gpt4 key购买 nike

我已经导入了 github's来自《Java 8 In Action》一书的项目在intellij中作为maven项目。

模块结构如下:

enter image description here

然后,我直接从 Intellij 执行 ExecuteAround 类的 Main 方法(右键单击 -> 执行 main...)

public static void main(String ...args) throws IOException{

// method we want to refactor to make more flexible
String result = processFileLimited();
System.out.println(result);

System.out.println("---");

String oneLine = processFile((BufferedReader b) -> b.readLine());
System.out.println(oneLine);

String twoLines = processFile((BufferedReader b) -> b.readLine() + b.readLine());
System.out.println(twoLines);

}

public static String processFileLimited() throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))) {
return br.readLine();
}
}


public static String processFile(BufferedReaderProcessor p) throws IOException {
try(BufferedReader br = new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))){
return p.process(br);
}

}

public interface BufferedReaderProcessor{
public String process(BufferedReader b) throws IOException;

}

然后,我收到 FileNotFoundException:

Exception in thread "main" java.io.FileNotFoundException: lambdasinaction\chap3\data.txt

如果执行“maven package”,在 jar 中,data.txt 文件直接包含在 chap3 文件夹/包中,但如果执行,我会得到相同的错误:

java -classpath lambdasinaction-1.0.jar lambdasinaction.chap3.executeAround
Exception in thread "main" java.io.FileNotFoundException: lambdasinaction\chap3\data.txt (Le chemin d?accès spécifié est introuvable)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at lambdasinaction.chap3.ExecuteAround.processFileLimited(ExecuteAround.java:23)
at lambdasinaction.chap3.ExecuteAround.main(ExecuteAround.java:9)

1- 为什么它不直接从 intellij 运行?文件正确地位于资源文件夹中。

2 - 这可能是最重要的:为什么直接从命令行执行程序时它没有运行?

感谢您的帮助

最佳答案

使用“src/main/resources/lambdasinaction/chap3/data.txt”而不是“lambdasinaction/chap3/data.txt”

关于java - maven:尝试使用 Intellij 从资源打开文件或使用带有 jar 的 java 命令时出现 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com