5

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?

lilmessi42
  • 313
  • 2
  • 3
  • 13
  • 1
    The `resources` folder is not typically part of a deployed application. When you deploy your application, the resources will be bundled into the jar file. You can't use a file chooser to browse the contents of that. – James_D Mar 10 '16 at 17:44
  • Okay, but how can I browse the contents of another folder that is part of the deployed application? – lilmessi42 Mar 10 '16 at 18:24
  • Can you explain more completely what you're trying to do? You use a file browser to let the user browse the file system; the point being that the contents of the file system are unknown when you build the application. The available resources are known when you compile and build the application. So typically you don't browse for resources; resources are selected based on the state of the application. So the user does things in the UI that change the state of the app, and your code chooses from a predetermined set of resources based on that state. – James_D Mar 10 '16 at 18:51
  • My program allows the user to create and view certain xml files. I would like these files to be saved to a certain location, which was temporarily the resources folder. I have changed this location to a separate folder called 'records'. I want the user to be able to save and open files from this location, and am attempting to achieve this using a FileChooser with 'records' set as its inital directory. – lilmessi42 Mar 10 '16 at 19:49

1 Answers1

7

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);
James_D
  • 201,275
  • 16
  • 291
  • 322