Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set initial directory of JavaFX FileChooser

I would like to allow users of my program to open files only from a certain directory in the project folder. On Stack Overflow, I often find the following solution: chooser.setInitialDirectory(new File(System.getProperty("user.home"));, but I am trying to reference the resources folder in project. I tried to use fileChooser.setInitialDirectory(new File("/resources/")); but I get java.lang.IllegalArgumentException: Folder parameter must be a valid folder. How can I fix this problem?

like image 367
lilmessi42 Avatar asked Mar 10 '16 17:03

lilmessi42


1 Answers

The resources folder, and basically anything that becomes part of your deployed application, is not writable or browsable at runtime. Essentially, when you deploy your application, everything you need to run the application is bundled into an archive file, so resources is not really a folder at all, it's an entry in an archive. You cannot write to or browse such locations.

If you want the user to be able to save files to a specific location, you should define such a location: typically you would make this a subdirectory of the user's home directory. So, for example, you might do:

File recordsDir = new File(System.getProperty("user.home"), ".myApplicationName/records");
if (! recordsDir.exists()) {
    recordsDir.mkdirs();
}

// ...

FileChooser chooser = new FileChooser();
chooser.setInitialDirectory(recordsDir);
like image 82
James_D Avatar answered Sep 24 '22 08:09

James_D