为 Java 作业作业编写了一个基本文件处理程序,当我收到作业时,我有一些关于未能捕获一些实例的注释:
- 来自文件的缓冲区可能为空。
- 找不到文件
- 文件流未关闭
这是用于打开文件的代码块:
/**
* 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);
}
我从他那里得到的一个评论是fin.close();
需要在一个finally
街区内,而我根本没有。但我认为我创建 try/catch 的方式可以防止文件无法打开的问题。
让我澄清几件事:这不是针对当前的作业(不是试图让别人做我自己的工作),我已经创建了我的项目并已对其进行评分。我自己并没有完全理解教授的推理。最后,我没有很多Java经验,所以我有点困惑为什么我catch
的不够好。