[英]opening a javafx FileChooser in the user directory
我试图根据我在这里找到的一个例子在用户目录中打开一个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中,不知道其他平台。
这就是我最终做的事情,它就像一个魅力。
此外,请确保在尝试阅读时可以访问您的文件夹(良好做法)。 您可以创建该文件,然后检查是否可以读取它。 如果您无法访问用户目录,则完整代码将如下所示,默认为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,但在其他操作系统上可能有所不同(未经测试)
尝试:
String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.