FileNotFoundException尽管canRead()和exists()返回true

时间:2013-03-07 06:04:36

标签: java file exception filereader

我这样做并将一些内容写入此文件。

fileSymbol = new File("D:\\TempFiles\\SymbolFile.xml");
fileSymbol.createNewFile();
prSymbol = new PrintWriter(fileSymbol);
while(//condition goes here){
   prSymbol.write(text);
}

然后我尝试从这个文件中读取,

FileReader fr = new FileReader(fileSymbol);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();

当我尝试运行时,它会出现以下异常

java.io.FileNotFoundException: fileSymbol (The system cannot find the file specified)

当我尝试

fileSymbol.canRead();
fileSymbol.exists();

两者都返回true。

虽然我已经创建了该文件,但我不明白为什么会出现此错误。当我手动检查位置时,我能够看到我创建的文件。

PS:我刚刚提供了代码的代码片段。

2 个答案:

答案 0 :(得分:4)

在阅读文件之前添加以下内容

  prSymbol.close();

在关闭之前不需要调用flush()。参考JavaDoc - close()

答案 1 :(得分:3)

  

java.io.FileNotFoundException:fileSymbol(系统找不到指定的文件)

如果您准确转录了该消息,则只能表示您使用"fileSymbol"作为文件名,之前您使用的是"D:\\TempFiles\\SymbolFile.xml"

在为同一文件创建输出流或编写器之前,NB调用createNewFile()行是完全浪费时间。

相关问题