Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JAR: Writing to a file

Tags:

java

eclipse

jar

Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?

like image 502
well actually Avatar asked Dec 08 '25 22:12

well actually


2 Answers

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?

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). In eclipse, configure the working directory from within the run configuration dialog.

like image 174
squawknull Avatar answered Dec 11 '25 11:12

squawknull


You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.

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:

// 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.

like image 37
Martijn Courteaux Avatar answered Dec 11 '25 10:12

Martijn Courteaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!