【问题标题】:Expression file.exists() returns true, reading file fails with FileNotFoundException表达式 file.exists() 返回 true,读取文件失败并出现 FileNotFoundException
【发布时间】:2014-12-01 11:24:24
【问题描述】:

方法返回FileNotFoundException

String statSource = 'some path';
 try {

         File file = new File(statSource);

         if (!file.exists())
         {
             System.out.println(file.getPath() + " doesn't exist!");
         }
         else
         {
             System.out.println("OK!");
         }


         // otevření CSV
         csv = new CsvReader(statSource, ';', Charset.forName("windows-1250"));
     }

起初我得到“好的!”消息,但在最后一行我得到FileNotFoundException。文件位于本地硬盘上。

你知道出了什么问题吗?

【问题讨论】:

  • 无论文件是否存在,您的CsvReader 都会进行初始化。
  • statsource路径是目录还是文件?
  • FileNotFoundException 是 JDK 最无用的例外,因为当文件存在但您无法读取/写入它时,您也会得到它。因此,发布完整的堆栈跟踪:只有相关的消息可能会给出提示。

标签: java netbeans-7 filenotfoundexception


【解决方案1】:

假设您正在谈论 this class,并且您使用的是 JDK 7,请帮自己一个忙并使用它:

final Path csvpath = Paths.get(statSource);

try (
    final InputStream in = Files.newInputStream(csvpath);
    final CsvReader csv = new CsvReader(in, ';', Charset.forName("windows-1250");
) {
    // operate on csv
}

如果文件不存在或其他什么,你至少会得到一个有意义的异常:AccessDeniedExceptionNoSuchFileException等;他们都继承了FileSystemException

【讨论】:

  • java.nio.file.NoSuchFileException: C:\Users\medm\Documents\Rocenka\Rocenka_2014_test_listopad\Rocenka_2014_priprava\data\2014\2014-oprava_ST055.csv at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:229) at java.nio.file.Files.newByteChannel(Files.java:315) at java.nio.file.Files.newByteChannel(Files.java:361)
  • 现在你知道问题所在了;)
【解决方案2】:

FileNotFoundException - 如果给定的文件对象不表示 现有的可写常规文件和该名称的新常规文件 无法创建,或者如果在打开或 创建文件

所以FileNotFoundException可能会在以下3种情况下抛出。

  1. 文件不存在。
  2. 文件实际上是一个目录。
  3. 由于某种原因无法打开命名文件进行读取,比如权限

因此,请确保您在操作文件而不是目录,然后尝试使用 file.canRead()(虽然在 Windows 上不够可靠,请参阅 bug)来测试它的 #3。

【讨论】:

  • 不幸的是,即使.canRead() 也不可靠。我已经多次看到它在 Windows 上失败了。
  • @fge,是的,但值得一试。我会在我的回答中更新它。
【解决方案3】:

我认为您只是将文件名提供给 csvReader。要在 java 中读取文件,您必须使用 FileReader。

你能不能把最后一行改成,

csv = new CsvReader(new FileReader(statSource), ';', Charset.forName("windows-1250"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    相关资源
    最近更新 更多