5

I want to change JFileChooser start directory to desktop. So, in my computer I wrote:

JFileChooser fc = new JFileChooser("C:\\Users\\LNK\\Desktop");

The problem is, when I compile my code and run program in another computer it doesn't work because there are no C:\\Users\\LNK\\Desktop path. So, is there some kind of "apsolute" path of desktop?

lnk
  • 593
  • 2
  • 11
  • 27

3 Answers3

13

You can use a user.home system property to get user directory. So your code would look like

String userDir = System.getProperty("user.home");
JFileChooser fc = new JFileChooser(userDir +"/Desktop");
Eugene Ryzhikov
  • 17,131
  • 3
  • 38
  • 60
  • 2
    I think you mean `System.getProperty("user.home")`. Concatenating "/Desktop" will work on Windows, Mac OS X, and even Linux. – martinez314 Mar 18 '14 at 21:33
3

Here is another option for getting to the Windows desktop:

fileChooser.setCurrentDirectory(new File("C:\\"));
Action details = fileChooser.getActionMap().get("Go Up");
details.actionPerformed(null);
details.actionPerformed(null);

If you leave off the last line, you will get to "Computer"

Tim Penner
  • 3,551
  • 21
  • 36
0

use this ,

String desktopPath = WindowsUtils.getCurrentUserDesktopPath();
RKC
  • 1,834
  • 13
  • 13