Have you ever seen a Java File close() throw an exception?

前端 未结 8 879
野性不改
野性不改 2020-12-31 00:10

Has anyone ever seen an exception thrown when calling close method on any closable object?

8条回答
  •  Happy的楠姐
    2020-12-31 00:25

    Old post and long since answered but here's a real example:

    The following code will except out when bufferedWriter.close() is called. This happens because the BufferedWriter's underlying Writer (the FileWriter) has already been closed and when a BufferedWriter closes, it first attempts to flush any data in its buffer to its underlying Writer.

    File newFile = new File("newFile.txt");
    
    FileWriter fileWriter = new FileWriter(newFile);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    
    bufferedWriter.write("Hello World");
    
    fileWriter.close();
    bufferedWriter.close();
    

    Note: If there's no data in the buffer [comment out the write() line or add a flush() call] then no exception will be generated

提交回复
热议问题