写了一个基本的文件处理程序一个Java家庭作业,而当我接到任务后,我有一些注意事项有关未能赶上了几个例子: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
不够好。
虽然在一个长时间运行的程序中关闭系统资源是非常重要的(当然这是很好的做法),如果你打算在yo中调用'System.exit',是否关闭文件是一个有争议的问题你的catch块。 – jasonmp85 2010-05-27 18:57:03
@ jasonmp85这就是我的想法,但是它看起来好像他希望我们把它标记为好像它会一直在运行。这对我来说很有意义。 – Urda 2010-05-27 19:36:45