How to get absolute path from FileDialog?
Asked Answered
H

2

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?

Holms answered 18/11, 2016 at 9:54 Comment(5)
fd.getFile();Triplicate
I know that. but it return just file name like "text.txt". I need full-path like "c://text.txt"Holms
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.Triplicate
Thanks. I tired to "File f = new FIle(fd.getFIle());" and I got Full-path.Holms
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 for many good reasons to abandon AWT components in favor of Swing.Redwine
P
3

Check out File.getAbsolutePath():

String path = new File(fd.getFile()).getAbsolutePath();
Pleasant answered 18/11, 2016 at 10:22 Comment(3)
This allways returned a path relative to the program running for me.Equilateral
Even when you include the getAbsolutePath() call? What OS are you on?Pleasant
Ubuntu 17.10. What worked for me was the answer below with the getDirectory callEquilateral
A
24

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.

Atlas answered 24/7, 2017 at 19:14 Comment(1)
It's probably better to use new File(fd.getDirectory(), fd.getFile()) than trying to concatenate the two components by hand.Reunite
P
3

Check out File.getAbsolutePath():

String path = new File(fd.getFile()).getAbsolutePath();
Pleasant answered 18/11, 2016 at 10:22 Comment(3)
This allways returned a path relative to the program running for me.Equilateral
Even when you include the getAbsolutePath() call? What OS are you on?Pleasant
Ubuntu 17.10. What worked for me was the answer below with the getDirectory callEquilateral

© 2022 - 2024 — McMap. All rights reserved.