有没有办法从 Java 中的 FileDialog 获取目录路径?

Is there a way to get directory path from FileDialog in Java?

我正在 Java 中构建一个简单的程序,总体而言我是 GUI 的新手。我试图打开一个 FileDialog 到 select 目录,并使用它的路径将文件发送到 selected 目录。但是,它不适用于 FileDialog。

现在,我尝试了 JFileChooser,但它一直挂起并且没有像 FileDialog 那样显示完整的 Mac OS X 对话框,我更喜欢使用后者。下面是我的 FileDialog 的代码。当我从对话框中 select 时如何获取 selected 目录并打印出来?我花了 2 天时间进行研究,但我找不到一个好的解决方案,它可以显示完整的 MAC OS X 对话框。

String osName = System.getProperty("os.name");
String homeDir = System.getProperty("user.home");
File selectedPath = null;
final JFileChooser fc = new JFileChooser();
if (osName.equals("Mac OS X")) {
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
    FileDialog fd = new FileDialog(new Frame(), "Choose a file", FileDialog.LOAD);
    fd.setDirectory(homeDir);
    fd.setVisible(true);
    String filename = fd.getDirectory();
    selectedPath = new File(filename);

    if (filename == null) {
        continue;
    } else {
        save_location = filename;
        dout.writeUTF("200"); //Status OK
        dout.flush();
        System.out.println(filename);
    }               
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
}

How can I get the selected directory and print it out when I select it from the dialog?

使用fd.getFile()获取目录名.e.g.

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;

public class Main {
    public static void main(String[] args) {
        String osName = System.getProperty("os.name");
        String homeDir = System.getProperty("user.home");
        File selectedPath = null;
        if (osName.equals("Mac OS X")) {
            System.setProperty("apple.awt.fileDialogForDirectories", "true");
            FileDialog fd = new FileDialog(new Frame(), "Choose a file", FileDialog.LOAD);
            fd.setDirectory(homeDir);
            fd.setVisible(true);
            String fileName = fd.getFile();
            System.out.println(fileName);
            File file;
            if (fileName != null) {
                file = new File(fd.getDirectory() + fileName);
                System.out.println("You selected "+file.getAbsolutePath());
            } else {
                System.out.println("You haven't selected anything");
            }
        }
    }
}

输出:当我selectDesktop然后按下Open

Desktop
You selected /Users/arvind.avinash/Desktop

备注:

  1. 使用 fd.getDirectory() 获取 selected 目录的父目录路径,即我的示例中的 /Users/arvind.avinash/
  2. 使用 fd.getFile() 获取 selected 目录的名称,即我的示例中的 Desktop
  3. 使用组合 fd.getDirectory() + fd.getFile() 获取 selected 目录的完整路径,即我示例中的 /Users/arvind.avinash/Desktop