java - 创建 .jar 和 FileNotFoundException

标签 java jar filenotfoundexception

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
Scanner sc = new Scanner(reader);

我的代码可以在 ide 中运行,即使在项目文件的所有文件夹中我也有这个 file.txt 。我将项目导出到 3 个不同的 ide(netbeans、intellij idea、eclipse)中的 jar,然后我运行 jar 文件,但出现此错误(不幸的是,双击 jar 对我不起作用,所以我在 cmd 上使用 java -jar运行);

Exception in thread "main" java.io.FileNotFoundException: file.txt (the system cannot find the file specified)
    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)

如果我在代码中给出文件的完整路径,它就可以工作,但我会将项目发送给其他人,因此当我尝试诸如InputStream等解决方案时,文件夹将被更改。我得到nullpointerException。

最佳答案

在您的 jar 附近创建一个"file"文件夹并将文件放入其中。试试这个代码块:

String filePath = System.getProperty("user.dir")
        + File.separator
        + "files"
        + File.separator + "file.txt";
try {
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    Scanner sc = new Scanner(reader);
} catch (Exception e) {
    e.printStackTrace();
}

关于java - 创建 .jar 和 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61543906/

相关文章:

java - 如何在静态类中加载字体并用作 JAR

java - 查看jar.exe是否可用

java - 尽管文件存在,但 FileNotFoundException

java - hibernate 5.2 : how to map set of enums by name using hbm file

java - 陷入解析 JSON 的困境

java - 如何将 "jar"转换为 Linux 可执行文件?

java - 导出 .jar 时出现 FileNotFoundException

java - 如何使用 FileInputStream 加载配置 xml 文件,但出现 FileNotFoundException

java - 访问者模式,并非所有访问者都对接口(interface)中的所有方法都有合理的实现

java - Java 中的 while 循环同时返回祝贺和抱歉消息