Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get absolute path from FileDialog?

Tags:

java

file

awt

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?

like image 527
Nick Avatar asked Nov 18 '16 09:11

Nick


2 Answers

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.

like image 61
rsa Avatar answered Oct 31 '22 13:10

rsa


Check out File.getAbsolutePath():

String path = new File(fd.getFile()).getAbsolutePath();
like image 22
Thomas Avatar answered Oct 31 '22 13:10

Thomas