如何从FileDialog获取绝对路径?

Nic*_*ick 8 java file awt

我正在创建FileDialog并尝试获取FilePath for FileDialog对象.

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

在这段代码中,我需要获得一个绝对的FilePath来与File对象一起使用.在这种情况下如何获取文件路径?

rsa*_*rsa 15

您可以将FileDialog.getDirectory()FileDialog.getFile()组合以获取完整路径.

String path = fd.getDirectory() + fd.getFile();
File f = new File(path);
Run Code Online (Sandbox Code Playgroud)

我需要使用上面而不是对File.getAbsolutePath()的调用,因为getAbsolutePath()返回当前工作目录的路径而不是FileDialog中选择的文件的路径.


Tho*_*mas 3

查看File.getAbsolutePath()

String path = new File(fd.getFile()).getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

  • 这总是返回相对于为我运行的程序的路径。 (5认同)