【问题标题】:FileOutputStream inside runnable jar throwing FileNotFoundException if path contains folder如果路径包含文件夹,则可运行 jar 中的 FileOutputStream 抛出 FileNotFoundException
【发布时间】:2016-08-29 03:50:01
【问题描述】:

当使用 FileOutputStream 将对象输出到可运行 jar 中的文件夹时,您将收到 FileNotFoundException

将抛出 FileNotFoundException 的示例代码(目录或文件是否存在):

        ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("res/followers.txt"));
        wf.writeObject(crntFollowers);
        wf.flush();
        wf.close();
        writeSettingFollowers(crntFollowers.size());

但是,当使用相同的代码而不向路径添加“文件夹”时,您不会收到 FileNotFoundException,但根本不会创建文件

不会抛出 FileNotFoundException 的示例代码:

        ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("followers.txt"));
        wf.writeObject(crntFollowers);
        wf.flush();
        wf.close();
        writeSettingFollowers(crntFollowers.size());

这两个代码 sn-ps 在 Eclipse 中编译时都可以工作,但不能作为可运行的 jar,我猜这是由于路径不同,但我不知道如何修复它。

那么,我怎样才能将对象写入可运行 jar 中的文件夹,而不会出现 FileNotFoundException 并且文件也会被创建?

【问题讨论】:

    标签: java jar runnable filenotfoundexception fileoutputstream


    【解决方案1】:

    你错了。

    1. 您不能使用FileOutputStream 或实际上以任何其他形式或形式在运行的 JAR 中创建文件。
    2. 文件在没有异常的情况下被创建,但是在当前工作目录中,而不是在JAR文件中。

    【讨论】:

    • 谢谢,我已经更改了我的代码,现在可以使用了 :)
    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2018-07-27
    • 2013-12-08
    • 2023-03-27
    • 2012-02-15
    相关资源
    最近更新 更多