java practices -_ always close streams

2
Alway s close streams Stream s represent resources whi ch y ou m ust alway s cl ean up expl i ci tl y , by cal l i ng th e close m ethod. Som e java.io cl asses (apparent l y ju st t he ou tpu t cl asses) incl ude a flush m ethod. When a close m ethod is called on a such a class, it automati cal l y perf orm s a flush. There i s no need to expl icitl y call flush bef ore cal l i ng close. One stream i s chai ned to another by passi ng it to the constructor of som e second stream. When thi s second stream is cl osed, then i t autom ati cally cl oses the ori g inal underl y i ng stream as wel l . If m ulti  pl e stream s are chai ned tog ether, then cl osi n g the one whi ch was the l ast to be constructed, and is thus at the hi g hest l evel of  abstraction, wi ll autom atical l y cl ose al l the underl y i ng streams. So, one only has to call close on one stream in order to cl ose (and f lush, if  applicabl e) an enti re seri es of related streams. Example import java.io.*; import java.util.*; import java.util.logging.*;  publ ic class ExerciseSerializable {   publ ic static void main(String... aArguments) { //create a Serializable List List<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 List List<String> recoveredQuarks = (List<String>)input.readObject();  //display its data  for(String quark: recoveredQuarks){

Upload: ddzako9140

Post on 05-Apr-2018

213 views

Category:

Documents


0 download

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