简体   繁体   English

Java JAR:写入文件

[英]Java JAR: Writing to a file

Currently, in my eclipse project, I have a file that I write to. 目前,在我的eclipse项目中,我有一个我写的文件。 However, I have exported my project to a JAR file and writing to that directory no longer works. 但是,我已将项目导出到JAR文件,并且写入该目录不再有效。 I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter? 我知道我需要将此文件视为类路径资源,但如何使用BufferedWriter执行此操作?

You shouldn't have to treat it as a classpath resource to write to a file. 您不必将其视为要写入文件的类路径资源。 You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you? 如果文件在您的JAR文件中,您只需要这样做,但是您不想写入JAR文件中包含的文件吗?

You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). 您仍然可以创建和写入文件,但它可能是相对于工作目录 - 您执行JAR文件的目录(除非您使用绝对路径)。 In eclipse, configure the working directory from within the run configuration dialog. 在eclipse中,从运行配置对话框中配置工作目录。

You're probably working in Linux. 你可能在Linux上工作。 Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). 因为,在Linux中,当您从JAR启动应用程序时,工作目录将设置为您的主文件夹(/ home / yourname /)。 When you start it from Eclipse, the working directory is set to the project folder. 从Eclipse启动时,工作目录设置为项目文件夹。

To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files: 要确保您确实知道您正在使用的文件位于项目文件夹或JAR所在的文件夹中,您可以使用这段代码来了解JAR所在的位置,然后使用File(File parent, String name)构造函数来创建文件:

// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);

And, from now on, you can create all your File's like this: 而且,从现在开始,您可以像这样创建所有文件:

File myFile = new File(root, "config.xml");

Of course, root has to be in your scope. 当然, root必须在你的范围内。

Such resources (when altered) are best stored in a sub-directory of user.home . 这些资源(更改时)最好存储在user.home的子目录中。 It is a reproducible path that the user should have write access to. 这是一个可重现的路径,用户应具有写入权限。 You might use the package name of the main class as a basis for the sub-directory. 您可以使用主类的包名作为子目录的基础。 EG 例如

our.com.Main -> ${user.home}/our/com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM