如何从 FileDialog 获取绝对路径?

How to get absolute path from FileDialog?

我正在创建 FileDialog 并尝试获取 FileDialog 对象的 FilePath。

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

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

查看 File.getAbsolutePath():

String path = new File(fd.getFile()).getAbsolutePath();

您可以组合 FileDialog.getDirectory() with FileDialog.getFile() 以获得完整路径。

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

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