【发布时间】:2014-08-09 04:32:13
【问题描述】:
首先我知道我应该对资源使用 try-catch,但是目前我的系统上没有最新的 JDK。
我有下面的代码,并试图确保资源 reader 使用 finally 块关闭,但是下面的代码由于两个原因无法编译。首先是 reader 可能尚未初始化,其次 close() 应该在它自己的 try-catch 中被捕获。这两个原因都不会破坏初始 try-catch 块的对象吗?
我可以通过将 finally 块 close() 语句放在它自己的 try-catch 中来解决这个问题。但是这仍然会留下关于阅读器未初始化的编译错误?
我假设我在某个地方出错了?感谢您的帮助!
干杯,
public Path [] getPaths()
{
// Create and initialise ArrayList for paths to be stored in when read
// from file.
ArrayList<Path> pathList = new ArrayList();
BufferedReader reader;
try
{
// Create new buffered read to read lines from file
reader = Files.newBufferedReader(importPathFile);
String line = null;
int i = 0;
// for each line from the file, add to the array list
while((line = reader.readLine()) != null)
{
pathList.add(0, Paths.get(line));
i++;
}
}
catch(IOException e)
{
System.out.println("exception: " + e.getMessage());
}
finally
{
reader.close();
}
// Move contents from ArrayList into Path [] and return function.
Path pathArray [] = new Path[(pathList.size())];
for(int i = 0; i < pathList.size(); i++)
{
pathArray[i] = Paths.get(pathList.get(i).toString());
}
return pathArray;
}
【问题讨论】: