Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jfilechooser - set directory to a path in a file

I am trying to set the directory path in JFilechooser through something like this(using commons-io ) :

String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File theDirectory = new File(fileContents);

filechooser = new JFileChooser();
fileChooser.setCurrentDirectory(theDirectory);
filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

I'm using getCanonicalPath() to get the path and write in the file path.txt

path = file.getCanonicalPath();

I don't intend to put all my code here,but I'm sure that the program writes and reads the path in path.txt. I don't get any error,but everytime I run the program it always open JFilechooser in my documents folder.What i am doing wrong?

like image 795
fermk090 Avatar asked Apr 19 '11 19:04

fermk090


2 Answers

Try to pass the current directory directly in the constructor:

filechooser = new JFileChooser(theDirectory);
like image 173
Heisenbug Avatar answered Oct 11 '22 10:10

Heisenbug


If you consult the API, using the default constructor (i.e. new JFileChooser()):

Constructs a JFileChooser pointing to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.

This would seem to account for always opening to My Documents, but this isn't your problem. In fact, your problem lies with setting the current directory (i.e. setCurrentDirectory(theDirectory)):

Sets the current directory. Passing in null sets the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix. If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.

That being said, I'd pay attention to the highlighted text since it appears that you're setting a file as the current directory and not a directory.

like image 40
mre Avatar answered Oct 11 '22 08:10

mre