为什么找不到File im open,因为File存在

问题描述 投票:2回答:3

我读了一个由JFileChooser选择的文件,这意味着该文件存在,我知道它在那里,但我仍然得到一个FileNotFoundException。

我硬编码了这个文件的路径,并且工作正常。


JFileChooser chooser = new JFileChooser();
int rueckgabeWert = chooser.showOpenDialog(null);

if (rueckgabeWert == JFileChooser.APPROVE_OPTION)
{
  filetoopen = chooser.getSelectedFile().getName();
  Path path = Paths.get(filetoopen);
  List<String> allLines = null;
  try
  {
    allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
  }
  catch (IOException e1)
  {
    e1.printStackTrace();
  }

  for (int i = 0; i < allLines.size(); i++)
  {
    System.out.println(allLines.get(i));
  }

}

如何让文件正确打开文件?

java filenotfoundexception
3个回答
1
投票

什么是filetoopen,是文件吗?通过行chooser.getSelectedFile().getName()你只是告诉JFileChooser只是得到文件的名称,你应该尝试用getAbsolutePath()而不是getName()。并且还通过chooser.showOpenDialog(null);改变chooser.showOpenDialog(chooser);。我希望它对你有所帮助。


2
投票

chooser.getSelectedFile().getName()返回文件的名称。您需要获取文件的完整路径才能打开它。

请改用chooser.getSelectedFile().getAbsolutePath()


2
投票

如前所述,getName()返回文件的名称,而不是路径。 如果你想通过Path打开文件,你可以使用toPath()File函数:

...
File filetoopen = chooser.getSelectedFile();
List<String> allLines = null;
try {
    allLines = Files.readAllLines(filetoopen.toPath(), StandardCharsets.UTF_8);
} catch (IOException e1) {                          
    e1.printStackTrace();
}
...
© www.soinside.com 2019 - 2024. All rights reserved.