10

I'm creating FileDialog and trying to get a FilePath for FileDialog object.

FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD); 
fd.setVisible(true);
String path = ?;
File f = new File(path);

In this codes, I need to get a absolute FilePath for using with File object. How can I get filepath in this situation?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nick
  • 139
  • 2
  • 9
  • `fd.getFile();` – kaqqao Nov 18 '16 at 10:17
  • 1
    I know that. but it return just file name like "text.txt". I need full-path like "c://text.txt" – Nick Nov 18 '16 at 10:18
  • I'm pretty sure it gives you a path relative to the initial directory, which if you don't set, will be the current user's home directory. So just set the intial directory explicitly: `fd.setDirectory("C://");` and treat all paths you get as relative to that. – kaqqao Nov 18 '16 at 10:21
  • Thanks. I tired to "File f = new FIle(fd.getFIle());" and I got Full-path. – Nick Nov 18 '16 at 10:23
  • 1
    1) `File f = fd.getFiles()[0];` but check the array is not of 0 length (meaning no file selected) before doing that. 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. – Andrew Thompson Nov 18 '16 at 16:18

2 Answers2

23

You can combine FileDialog.getDirectory() with FileDialog.getFile() to get a full path.

String path = fd.getDirectory() + fd.getFile();
File f = new File(path);

I needed to use the above instead of a call to File.getAbsolutePath() since getAbsolutePath() was returning the path of the current working directory and not the path of the file chosen in the FileDialog.

rsa
  • 585
  • 4
  • 16
  • 1
    It's probably better to use `new File(fd.getDirectory(), fd.getFile())` than trying to concatenate the two components by hand. – saagarjha Jul 21 '21 at 11:15
3

Check out File.getAbsolutePath():

String path = new File(fd.getFile()).getAbsolutePath();
Thomas
  • 17,016
  • 4
  • 46
  • 70