如果路径包含文件夹,可运行 jar 中的 FileOutputStream 抛出 FileNotFoundException
FileOutputStream inside runnable jar throwing FileNotFoundException if path contains folder
当使用 FileOutputStream 将对象输出到可运行 jar 内的文件夹时,您将得到 FileNotFoundException
将抛出 FileNotFoundException 的示例代码(无论目录或文件是否存在):
ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("res/followers.txt"));
wf.writeObject(crntFollowers);
wf.flush();
wf.close();
writeSettingFollowers(crntFollowers.size());
但是,当使用相同的代码但不向路径添加 'folder' 时,您不会得到 FileNotFoundException,但根本不会创建文件
不会抛出 FileNotFoundException 的示例代码:
ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("followers.txt"));
wf.writeObject(crntFollowers);
wf.flush();
wf.close();
writeSettingFollowers(crntFollowers.size());
这两个代码片段在 Eclipse 中编译时都有效,但不是作为可运行的 jar,我猜这是由于不同的路径,但我不知道如何修复它。
那么,如何在不获取 FileNotFoundException 的情况下将对象覆盖到可运行 jar 中的文件夹,并且还创建了文件?
你错了
- 您不能在 运行 个具有
FileOutputStream
的 JAR 中创建文件,实际上也不能以任何其他方式创建文件。
- 如果没有异常,文件将创建,但在当前工作目录中,而不是在 JAR 文件中。
当使用 FileOutputStream 将对象输出到可运行 jar 内的文件夹时,您将得到 FileNotFoundException
将抛出 FileNotFoundException 的示例代码(无论目录或文件是否存在):
ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("res/followers.txt"));
wf.writeObject(crntFollowers);
wf.flush();
wf.close();
writeSettingFollowers(crntFollowers.size());
但是,当使用相同的代码但不向路径添加 'folder' 时,您不会得到 FileNotFoundException,但根本不会创建文件
不会抛出 FileNotFoundException 的示例代码:
ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("followers.txt"));
wf.writeObject(crntFollowers);
wf.flush();
wf.close();
writeSettingFollowers(crntFollowers.size());
这两个代码片段在 Eclipse 中编译时都有效,但不是作为可运行的 jar,我猜这是由于不同的路径,但我不知道如何修复它。
那么,如何在不获取 FileNotFoundException 的情况下将对象覆盖到可运行 jar 中的文件夹,并且还创建了文件?
你错了
- 您不能在 运行 个具有
FileOutputStream
的 JAR 中创建文件,实际上也不能以任何其他方式创建文件。 - 如果没有异常,文件将创建,但在当前工作目录中,而不是在 JAR 文件中。