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 中的一个错误:https ://bugs.openjdk.java.net/browse/JDK-8098160 (您需要创建一个免费的 Jira 帐户才能查看错误报告)。这个问题发生在 OSX 中,不知道其他平台。

4

3 回答 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,但在其他操作系统上可能会有所不同(未经测试)

于 2013-01-17T20:16:46.450 回答
1

尝试:

String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
于 2013-01-12T02:41:51.493 回答
-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);   
    }

  }
于 2017-07-04T20:14:28.957 回答