新的FileInputStream(templateFile);初始化后调用close()?

时间:2012-04-28 12:27:30

标签: java fileinputstream

构造函数new FileInputStream(someFile);在初始化后是否调用close()方法?初始化后我需要在这个对象上调用close()吗?

3 个答案:

答案 0 :(得分:1)

不,它只是打开了流;由你决定何时关闭它。

答案 1 :(得分:1)

不,构造函数不会调用close()方法,因此在使用特定的FileInputStream实例时应该调用它。

答案 2 :(得分:1)

如果您忘记这样做,文件通常会在程序终止时或文件流对象被垃圾收集时自动关闭,但最好在完成后立即关闭文件。

File file = new File("DevFile.txt"); // This will create file object with meta info

int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;

try {
fin = new FileInputStream(file); // It'll open a stream and type is input

while ((ch = fin.read()) != -1)// and you can read data stream unless it is closed
strContent.append((char) ch);

fin.close(); // you should close stream to provide safety of your file 

} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}