gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:54:16 25 4
gpt4 key购买 nike

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

现在,我尝试了 JFileChooser,它一直挂起,并且不像 FileDialog 那样显示完整的 Mac OS X 对话框,我更喜欢使用后者。下面是我的文件对话框的代码。当我从对话框中选择目录时,如何获取所选目录并将其打印出来?我花了 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()获取目录名称,例如

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
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示例。

关于java - 有没有办法从Java中的FileDialog获取目录路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com