0

So I've created just a simple application which I'm using to apply for a highschool internship. It was built using Eclipse.

I initially exported into a runnable .jar file, but the location I initially saved files, ("src/fileDirectories") didn't work on export.I then set the location to "./fileDirectories") which works and the app can actually run, however the .jar file creates the folder directory in the same folder as the .jar file.

This isn't too bad, as I can create a folder with the .jar and the saved files in it, which is fine, but similar to images, I'm wondering if there is a way to save .txt files in a directory to the .jar file so everything works with just the .jar application.

  • ... what's the question? – user202729 Jan 20 '18 at 16:16
  • to simplify sorry, how can i use file i/o within the .jar file? Right now the directory I'm accessing is outside the .jar. I want to know if the directory can be made to be inside the .jar file so that is all you see. – Andrew Garneau Jan 20 '18 at 16:29

1 Answers1

0

Assuming the files you want to access are static, and are not changed by the application, you can do this using the classpath.

When you access a file using new File("path"), Java will look for it in the file system, relative to the working directory (i.e. where the application was launched from.

An alternative way to access files is to look them up from the classpath - this is the list of locations Java searches for resources. It includes, among other things, the top level of your JAR archive. You can access this as follows:

this.getClass().getResourceAsStream("/my_file.txt")

Build tools will generally have preconfigured directories (e.g. src/main/resources) which get copied from your source tree into the JAR so they can be accessed in this way.

This is great if you have some static resources or config which you want to access at runtime, but don't want to have to pass around with your application. However, if what you want is a working folder for files which your application will make changes to or create new instances of, like user documents, you don't want this to be editing the JAR - you'll need to make a separate folder for these.

hugh
  • 2,237
  • 1
  • 12
  • 25
  • Okay thanks for the info! The app saves information that the user enters in a text field, over the terms of a year and saves it into certain directories. Since I'm adding and editing the files, the best way then seems to be to have a folder outside of the .jar file, correct? – Andrew Garneau Jan 20 '18 at 16:34
  • @AndrewGarneau Indeed, that's the only way. – James_D Jan 20 '18 at 16:49
  • Yes, definitely. A file is a good place for it, but you might want to consider using a database for a future version. – hugh Jan 20 '18 at 16:51