Java文件处理,我做错了什么?

Urd*_*rda 2 java filehandle

为Java Homework任务编写了一个基本的文件处理程序,当我收到作业时,我有一些关于未能捕获一些实例的注意事项:

  • 来自文件的缓冲区可能为null.
  • 找不到档案
  • 文件流未关闭

以下是用于打开文件的代码块:

/**
 * Create a Filestream, Buffer, and a String to store the Buffer.
 */
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;

/** Try to open the file from user input */
try
{
    fin = new FileInputStream(programPath + fileToParse);
    buffRead = new BufferedReader(new InputStreamReader(fin));
    loadedString = buffRead.readLine();
    fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
    System.err.println("CRITICAL: Unable to open text file!");
    System.err.println("Exiting!");
    System.exit(-1);
}
Run Code Online (Sandbox Code Playgroud)

我从他那里得到的一个评论是fin.close();需要处于一个finally区块中,而我根本没有.但我认为我创建try/catch的方式可以避免文件无法打开的问题.

让我明白一些事情:这不是当前的任务(不是试图让某人做我自己的工作),我已经创建了我的项目并且已经对它进行了评分.我自己并不完全理解教授的推理.最后,我没有很多Java经验,所以我有点困惑为什么我catch不够好.

aio*_*obe 7

  • 来自文件的缓冲区可能为null.

该文件可能为空.也就是说,打开文件时会到达文件结尾.loadedString = buffRead.readLine()然后会返回null.

也许你应该通过添加类似的东西来解决这个问题 if (loadedString == null) loadedString = "";

  • 找不到档案

正如FileInputStream(String)它的构造函数的文档中所解释的那样可能会抛出一个FileNotFoundException.你确实在你的IOException条款中捕获了这个(因为FileNotFoundException IOException),所以它很好,但你可能已经做到了:

} catch (FileNotFoundException fnfe) {
    System.err.println("File not fonud!");
} catch (IOException ioex {
    System.err.println("Some other error");
}
Run Code Online (Sandbox Code Playgroud)
  • 文件流未关闭

您可以调用fin.close()在正常情况下关闭文件流.也许他意味着它并不总是封闭的.将readLine可能引发IOException在这种情况下close()被跳过.这就是在一个finally子句中使用它的原因(无论在try-block中发生什么,都确保它被调用.(*)


(*)正如@mmyers正确指出的那样,因为你在-block中调用,所以放入close()一个finally块实际上是不够System.exit(-1)catch.如果这确实是所需的行为,则可以在catch子句中设置错误标志,如果设置了此标志,则在finally子句之后退出.