当 运行 java -jar project.jar 时找不到 file.txt 路径,但是当我从 Eclipse 或 NetBeans 启动相同的程序时它运行良好

Can't find file.txt path when running java -jar project.jar, but when i start same program from Eclipse or NetBeans it runs fine

//This is a method that can take path as argument or use the default one
public static Path getFile(Options options, String[] args, CommandLine cmd, CommandLineParser parser) throws ParseException{
    cmd = parser.parse(options, args);
    Path path;
    if (cmd.hasOption("a")) {
        path = Paths.get(cmd.getOptionValue("a"));
        return path;
    } else {
        Path destFilePath = Paths.get("resources\file.txt");
        return destFilePath;
    }
}

//This is where i parse the file and where i get Exception when i run it from cmd
public static Map<Integer,Log> parseFile(Path path){
    try(FileInputStream fileInputStream = new FileInputStream(path.toString());
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    ){ 
        String line;
        int counter = 0;
        Map<Integer,Log> logMap = new HashMap<>();
        while ((line = bufferedReader.readLine()) != null) {
            String[] array = line.split("\|");
            Log log = new Log(array[0], array[1], array[2], array[3], array[4]);
            logMap.put(counter++, log);
        }
        return logMap;
    } catch (FileNotFoundException fnfex) {
        System.out.println("File not found. Check the path and try again!");
        fnfex.printStackTrace();
    } catch (IOException ioex) {
        System.out.println("Could not read from file.");
        ioex.printStackTrace();
    }
    return null;
}

我有一个问题,我很难解决。我有一个 file.txt 需要读取和解析,我已将该文件包含到我的项目中。

当我从 Eclipse 运行 我的项目时它 运行 很好并且没有异常,但是当我尝试从 cmd 运行 同一个项目时我得到 java.io.FileNotFoundException .

如果我将 file.txt 从我的项目移动到桌面,然后输入 "C:\Users\Desktop\file.txt" 之类的路径,那么它 运行s 从 cmd 和 Eclipse 没有问题。我需要将 file.txt 包含在我的项目中

这是我从 cmd 运行 得到的,当我从 Eclipse 或 NetBeans 运行 得到的,参数相同 运行s 没有异常:

当您在 IDE 中 运行 时,它正在文件系统中查找文件。当您将文件打包到 Jar 中时,您需要从 Jar 中加载它。由于 Jars 是 Zip 存档,您不能像普通文件一样加载它。

调查Class.getResourceAsStream()

你可以这样做

InputStream in = this.getClass().getResourceAsStream("resources/file.txt");