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

时间:2020-03-08 12:41:00

标签: java macos swing awt

我正在用Java构建一个简单的程序,并且对GUI还是陌生的。我正在尝试打开FileDialog来选择目录,并使用其路径将文件发送到所选目录。但是,它不适用于FileDialog。

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

HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
           "Origin": "https://www2.sgx.com",
           "Referer": "https://www2.sgx.com/securities/securities-prices"}

# Start downloading stocks info from sgx
req = requests.get("https://api.sgx.com/securities/v1.1?excludetypes=bonds&params=nc,adjusted-vwap,b,bv,p,c,change_vs_pc,change_vs_pc_percentage,cx,cn,dp,dpc,du,ed,fn,h,iiv,iopv,lt,l,o,p_,pv,ptd,s,sv,trading_time,v_,v,vl,vwap,vwap-currency",
                   headers=HEADERS)
stocks = json.loads(req.text)
table = pd.DataFrame(stocks)

1 个答案:

答案 0 :(得分:1)

如何获取所选目录并在选择后将其打印出来 在对话框中?

使用fd.getFile()来获取目录的名称。例如

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");
            }
        }
    }
}

输出:当我选择Desktop然后按Open

Desktop
You selected /Users/arvind.avinash/Desktop

注释:

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