在用户目录中打开JavaFX文件选择器

9
我正在尝试按照我在这里找到的示例,在用户目录中打开javafx FileChooser。

这是我使用的简单代码片段:

FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);

然而,我一直收到以下警告(完整的文件路径已被截断):
Invalid URL passed to an open/save panel: '/Users/my_user'.  Using 'file://localhost/Users/my_user/<etc>/' instead.

我验证了file对象是否为现有目录,添加了以下代码行:
System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true

我不明白为什么会收到警告信息。

更新:

这似乎是JavaFX的一个bug:https://bugs.openjdk.java.net/browse/JDK-8098160 (您需要创建一个免费的Jira帐户来查看错误报告)。 此问题发生在OSX上,其他平台不确定。

3个回答

10

这就是我最终采取的方法,而且效果非常好。

此外,请确保在尝试读取它时您的文件夹是可访问的(良好的实践)。您可以创建该文件,然后检查是否可以读取它。完整代码如下,默认为 c: 驱动器,如果无法访问用户目录,则会使用该默认驱动器。

FileChooser fileChooser = new FileChooser();

//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);

//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
    userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);

//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
    path = chosenFile.getPath();
} else {
    //default return value
    path = null;
}

这适用于Windows和Linux,但在其他操作系统上可能会有所不同(未经测试)。


1

尝试:

String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);

-1
@FXML private Label label1; //total file path print
@FXML private Label labelFirst; //file dir path print

private String firstPath; //dir path save

public void method() {
    FileChooser fileChooser = new FileChooser();
    if (firstPath != null) {
        File path = new File(firstPath);
        fileChooser.initialDirectoryProperty().set(path);   
    } 
    fileChooser.getExtensionFilters().addAll(
            new ExtensionFilter("Text Files", "*.txt"),
            new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
            new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
            new ExtensionFilter("All Files", "*.*") );
    File selectFile = fileChooser.showOpenDialog(OwnStage);
    if (selectFile != null){
        String path = selectFile.getPath();
        int len = path.lastIndexOf("/"); //no detec return -1
        if (len == -1) {
            len = path.lastIndexOf("\\");
        }
        firstPath = path.substring(0, len);
        labelFirst.setText("file path : " + firstPath);
        label1.setText("First File Select: " + path);   
    }

  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接