创建.jar和FileNotFoundException

问题描述 投票:0回答:1
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。

编辑:提供类路径和资源可解决我的问题,如评论中提到的其他问题。

java jar filenotfoundexception
1个回答
0
投票

您好,在您的jar旁边创建一个“文件”文件夹,并将文件放在其中。尝试此代码块

        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();
        }
© www.soinside.com 2019 - 2024. All rights reserved.