我使用 JFileChooser
允许用户选择稍后将由我的程序处理的 .txt
文件,但是当用户选择该文件时,它实际上是由我的计算机默认应用程序(在我的例子中为 TeXworks)打开的,并由我的程序使用。知道如何阻止这个吗?
File fileToOpen = fileChooser.getSelectedFile();
最佳答案
JFileChooser
的 getSelectedFile()
方法返回 File
目的。
使用 getAbsolutePath()
获取文件的绝对名称。
修改后的示例来自 JavaDoc :
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
<小时/>
因此,在您的情况下,您只需将 .getAbsolutePath()
附加到语句末尾,如下所示:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();
关于java - 使用 JFileChooser 而不打开实际文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15057685/