java practices -_ always close streams
TRANSCRIPT
7/31/2019 Java Practices -_ Always Close Streams
http://slidepdf.com/reader/full/java-practices-always-close-streams 1/2
Alway s close streamsStream s represent resources whi ch you must alway s clean up expl icitly, by calling the close method.
Some java.io classes (apparentl y just the output cl asses) incl ude a flush method. When a close method
is called on a such a class, it autom atically perf orms a flush . There i s no need to expl icitly call flush bef orecalling close .
One stream is chained to another by passing it to the constructor of some second stream . When thi s second streamis closed, then i t autom atically cl oses the ori ginal underl ying stream as wel l.
If multi ple stream s are chai ned tog ether, then cl osing the one whi ch was the l ast to be constructed, and is thus at thehighest l evel of abstraction, wi ll autom atical ly close al l the underl ying stream s. So, one only has to call close onone stream in order to cl ose (and f lush, if applicabl e) an enti re seri es of related stream s.
Example
import java.io.*;import java.util.*;import java.util.logging.*;
public class ExerciseSerializable {
publ ic static void main(String... aArguments) {//create a Serializable ListList<String> quarks = Arrays.asList(
"up", "down", "strange", "charm", "top", "bottom");
//serialize the List//note the use of abstract base class references
try { //use buffering
OutputStream file = new FileOutputStream( "quarks.ser" );OutputStream buffer = new BufferedOutputStream( file );ObjectOutput output = new ObjectOutputStream( buffer );
try {output.writeObject(quarks);
} finally {
output.close();}
}catch (IOException ex){
fLogger.log(Level.SEVERE, "Cannot perform output.", ex);}
//deserialize the quarks.ser file //note the use of abstract base class references
try { //use buffering
InputStream file = new FileInputStream( "quarks.ser" );InputStream buffer = new BufferedInputStream( file );ObjectInput input = new ObjectInputStream ( buffer );
try {//deserialize the ListList<String> recoveredQuarks = (List<String>)input.readObject();
//display its data for (String quark: recoveredQuarks){
7/31/2019 Java Practices -_ Always Close Streams
http://slidepdf.com/reader/full/java-practices-always-close-streams 2/2
System.out.println("Recovered Quark: " + quark);}
} finally {
input.close();}
} catch (ClassNotFoundException ex){
fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex)}
catch (IOException ex){fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
}}
// PRIVATE //
//Use Java's logging facilities to record exceptions. //The behavior of the logger can be configured through a //text file, or programmatically through the logging API. private static final Logger fLogger =
Logger.getLogger(ExerciseSerializable. class .getPackage().getName())
;}
See Al so :
Finally and catchReading and wri ting text f ilesRecoveri ng resources
Woul d you use this techni que?
Yes No Undeci ded Vote