As indicated in the header, should I close the stream when reusing the FileOutputStream variable? For example, in the following codes, I have to call outfile.close()before assigning a new file to it, and why?
outfile.close()
Thanks:)
FileOutputStream outfile = null; int index = 1; while (true) { // check whether we should create a new file boolean createNewFile = shouldCreateNewFile(); //write to a new file if pattern is identified if (createNewFile) { /* Should I close the outfile each time I create a new file? if (outfile != null) { outfile.close(); } */ outfile = new FileOutputStream(String.valueOf(index++) + ".txt"); } if (outfile != null) { outfile.write(getNewFileContent()); } if (shouldEnd()) { break; } } try { if (outfile != null) { outfile.close(); } } catch (IOException e) { System.err.println("Something wrong happens..."); }
, " " FileOutputStream. , , - ( outfile ), . Java. , - FileOutputStream, , . , , - . FileOutputStream, null , .
FileOutputStream
outfile
null
close . ( , , .) , close IOException, , , , .
close
IOException
. (), . , (), , , ..
Java FileOutputStream.close()
, . .
java.
try-with-resources (. ), :
for (int index = 1; shouldCreateNewFile(); ++index) { FileOutputStream outfile = new FileOutputStream(index + ".txt"); try { outfile.write(getNewFileContent()); } finally { outfile.close(); } }
, Java 7 , . , :
for (int index = 1; shouldCreateNewFile(); ++index) { try (FileOutputStream outfile = new FileOutputStream(index + ".txt")) { outfile.write(getNewFileContent()); } }
The output stream will still be closed, but if trythere is an exception in the block and another when the stream is closed, the exception will be suppressed (associated with the main exception), and will not cause the main exception, as in the previous example.
try
You should always use automatic resource management in Java 7 or higher.
Source: https://habr.com/ru/post/1611689/More articles:Mediatek Linkit One Compilation error in Arduino IDE 1.6.6: arm-none-eabi-g ++: no such file or directory - arduino-idePassing code as an argument (C ++) - c ++Using Avrocoder for custom types using wagons - google-cloud-platformFinding a union how to configure the UDF insert function wizards and force UDF to manipulate other cells - debuggingCan the Apache Avro framework handle parameterized types during serialization? - javaHow is left shift of numbers greater than 32 bits? - javascripthttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1611691/robot-framework-using-relative-paths-to-run-tests-from-different-directory-variations&usg=ALkJrhiPGgqlvWjq5CBSJBgZSJybWSBb0QUsing the Facebook Graph API, you can determine if a page / page will be promoted / sponsored? - facebookComparison of difficulty values with oncoming - javaThe title bar is displayed in the middle of the page during screenshots on Selenium - pythonAll Articles