Java JFileChooser - 在当前目录中打开
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21534515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JFileChooser - open in current directory
提问by CodeGuy
I have a simple JFileChooser set up in the following manner
我按以下方式设置了一个简单的 JFileChooser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new FileFilter() {
...
});
int v = chooser.showOpenDialog(this);
if (v == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
}
As you can see, this FileChooser starts out in the current directory, which in my Netbeans project, is the root of the project folder. Here's the problem: When I select a file and it prints out the absolute path, it includes the "."
in the path. For instance, the output I get is:
如您所见,这个 FileChooser 从当前目录开始,在我的 Netbeans 项目中,它是项目文件夹的根目录。问题是:当我选择一个文件并打印出绝对路径时,它会"."
在路径中包含。例如,我得到的输出是:
/Users/MyName/Folder1/Folder2/./Temp.xls
Of course, this is weird, especially since I'm displaying this to the user. Now, I could be hacky and do some fun post substring processing stuff to get rid of that "/./"
portion. But...is there a non-lazy programmer way to fix this problem? Thanks in advance!
当然,这很奇怪,尤其是因为我要向用户显示它。现在,我可以做一些有趣的后期子字符串处理来摆脱那"/./"
部分。但是......有没有一种非懒惰的程序员方法来解决这个问题?提前致谢!
采纳答案by Nathaniel Jones
Use the system property "user.dir" as follows:
使用系统属性“user.dir”如下:
File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);