Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening a javafx FileChooser in the user directory

Tags:

java

javafx-2

I am trying to open a javafx FileChooser in the user directory according to an example I found here.

Here is a fragment of the simple code I am using:

FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);

However, I keep obtaining this warning (complete file paths have been truncated):

Invalid URL passed to an open/save panel: '/Users/my_user'.  Using 'file://localhost/Users/my_user/<etc>/' instead.

I verified that the file object is an existing directory adding these lines:

System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true

Then I do not have idea why I am obtaining the warning message.

UPDATE:

This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160 (you need to create a free Jira account to see the bug report). This problem happens in OSX, no idea about other platforms.

like image 219
Sergio Avatar asked Jan 10 '13 11:01

Sergio


2 Answers

This is what I ended up doing and it worked like a charm.

Also, make sure your folder is accessible when trying to read it (good practice). You could create the file and then check if you can read it. Full code would then look like this, defaulting to c: drive if you can't access user directory.

FileChooser fileChooser = new FileChooser();

//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);

//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
    userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);

//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
    path = chosenFile.getPath();
} else {
    //default return value
    path = null;
}

This works on Windows and Linux, but might be different on other operating systems (not tested)

like image 147
blo0p3r Avatar answered Oct 12 '22 08:10

blo0p3r


Try:

String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
like image 20
Kevin Avatar answered Oct 12 '22 08:10

Kevin