2011-12-02 30 views
0
final JFileChooser fc = new JFileChooser(); 
int returnVal = fc.showOpenDialog(this); 

if (returnVal == JFileChooser.APPROVE_OPTION) { 
    String fileName = fc.getSelectedFile().getName(); 
    String path = (new File(fileName)).getAbsolutePath(); 
} 

我得到的绝对路径是项目目录和文件名的拼接JFileChooser返回错误的文件名?

回答

2

JFileChooser.getSelectedFile()返回File对象。

为什么要获取文件名并再次实例化新的File对象?

你可以尝试:

fc.getSelectedFile().getAbsolutePath(); 
2

这就是getAbsolutePath()那样 - 得到的完整路径,包括驱动器盘符(如果你在Windows上),等什么是你想搞定,只是文件名?

后您初始化File对象,你可以从得到的只是文件名,或者您可以使用JFileChooser.getSelectedFile()

如果您收到/path/to/filefilename但你期待/path/to/file/filename那么你可以添加一个额外的斜杠适当的路径。

2

当然。因为您使用返回的文件名创建了新文件new File(fileName),这意味着相对路径。改为使用fc.getSelectedFile().getPath()fc.getSelectedFile().getAbsolutePath()

相关问题