【问题标题】:Does new FileInputStream(templateFile); invoke close() after initialization?是否 new FileInputStream(templateFile);初始化后调用close()?
【发布时间】:2012-04-28 12:27:29
【问题描述】:

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

【问题讨论】:

  • 如果确实如此,那就没有什么意义了。您将如何调用所有其他方法?

标签: java fileinputstream


【解决方案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) {
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      不,close() 方法不是由构造函数调用的,因此您应该在使用特定的 FileInputStream 实例完成后调用它。

      【讨论】:

        猜你喜欢
        • 2016-03-03
        • 2020-02-22
        • 1970-01-01
        • 2012-01-12
        • 2014-02-06
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多