Also if you're using Java 7, you can use a try-with-resources statement:
try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) {
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch(IOException readException) {
readException.printStackTrace();
}
Answer from Bugasu on Stack OverflowAlso if you're using Java 7, you can use a try-with-resources statement:
try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) {
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch(IOException readException) {
readException.printStackTrace();
}
It seems a bit clunky.
It is. At least java7's try with resources fixes that.
Pre java7 you can make a closeStream function that swallows it:
public void closeStream(Closeable s){
try{
if(s!=null)s.close();
}catch(IOException e){
//Log or rethrow as unchecked (like RuntimException) ;)
}
}
Or put the try...finally inside the try catch:
try{
BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
try{
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
}finally{
r.close();
}
}catch(IOException e){
e.printStackTrace();
}
It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.
The try-with-resources Statement
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
Source =>http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
From documentation:
The
finallyblock always executes when thetryblock exits. This ensures that the finally block is executed even if an unexpected exception occurs.The runtime system always executes the statements within the
finallyblock regardless of what happens within thetryblock. So it's the perfect place to perform cleanup.
So it means if you have some connection, stream or some other resources opened you have to be sure that they will be closed after your code block will be executed.
To avoid such ugly blocks you can use utility methods:
public void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ex) {
// handle block
}
}
}
Since Java 8 (but it is not required) you can provide your own Exception handler with closing resource:
public void close(Closeable closeable, Consumer<? extends Throwable> handler) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ex) {
handler.accept(ex);
}
}
}
Also, just for knowledge, there are two cases when finally block is not called. It means that in most cases it will be called.
You should use try-with-resource statements introduced in Java 7 rather than closing your streams on your own. Consider the following as an example :
try (
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(out))
) {
bufferedWriter.write(text);
} catch(IOException e) {
//log or propagate to the caller
}
Observe how you don't have to close the BufferedReader and BufferedWriter streams manually.
If you are using java6 or lower you could use a wrapper for you close().
public void closeStreams(Closeable c){
try{
c.close();
}
catch(IOException e){
}
finally{
// well noting here now..
}
}
And you can use :
finally {//cerrando muestras
if(muestras!=null){
muestras.closeStreams();
}
if(salida!=null){
salida.closeStreams();
}
}
Note that the following is only applicable for Java 6 and earlier. For Java 7 and later, you should switch to using try-with-resources ... as described in other answers.
If you are trying to catch and report all exceptions at source (in Java 6 or earlier), a better solution is this:
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(shapes);
oos.flush();
} catch (FileNotFoundException ex) {
// complain to user
} catch (IOException ex) {
// notify user
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException ex) {
// ignore ... any significant errors should already have been
// reported via an IOException from the final flush.
}
}
}
Notes:
- The standard Java wrapper streams, readers and writers all propagate
closeandflushto their wrapped streams, etc. So you only need to close or flush the outermost wrapper. - The purpose of flushing explicitly at the end of the try block is so that the (real) handler for
IOExceptiongets to see any write failures1. - When you do a close or flush on an output stream, there is a "once in a blue moon" chance that an exception will be thrown due to disc errors or file system full. You should not squash this exception!.
If you often have to "close a possibly null stream ignoring IOExceptions", then you could write yourself a helper method like this:
public void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ex) {
// ignore
}
}
}
then you can replace the previous finally block with:
} finally {
closeQuietly(oos);
}
Another answer points out that a closeQuietly method is already available in an Apache Commons library ... if you don't mind adding a dependency to your project for a 10 line method.
But be careful that you only use closeQuietly on streams where IO exceptions really are irrelevant.
UPDATE : closeQuietly is deprecated in version 2.6 of the Apache Commons API. Java 7+ try-with-resources makes it redundant.
On the issue of flush() versus close() that people were asking about in comments:
The standard "filter" and "buffered" output streams and writers have an API contract that states that
close()causes all buffered output to be flushed. You should find that all other (standard) output classes that do output buffering will behave the same way. So, for a standard class it is redundant to callflush()immediately beforeclose().For custom and 3rd-party classes, you need to investigate (e.g. read the javadoc, look at the code), but any
close()method that doesn't flush buffered data is arguably broken.Finally, there is the issue of what
flush()actually does. What the javadoc says is this (forOutputStream...)If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
So ... if you hope / imagine that calling
flush()guarantees that your data will persist, you are wrong! (If you need to do that kind of thing, look at theFileChannel.forcemethod ...)
Current best practice for try/catch/finally involving objects that are closeable (e.g. Files) is to use Java 7's try-with-resource statement, e.g.:
try (FileReader reader = new FileReader("ex.txt")) {
System.out.println((char)reader.read());
} catch (IOException ioe) {
ioe.printStackTrace();
}
In this case, the FileReader is automatically closed at the end of the try statement, without the need to close it in an explicit finally block. There are a few examples here:
http://ppkwok.blogspot.com/2012/11/java-cafe-2-try-with-resources.html
The official Java description is at:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
Best way is to use Java 7 and use try with resources, or do same thing manualy and add exception from closing as suppressed exception.
Pre Java 7: If you are throwing your custom exception, you can add in it supressed exception like it is done in Java 7 (in your exception create fields List suppressed and put there exceptions from close operation and when dealing with your exception, look there too. If you cannot do that, I don't know anything better than just log it.
examples: from Java tutorials
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
but better form is:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
This way even if creation of FileReader is succesfull but creation of BufferedReader fails (eg not enough memory), FileReader will be closed.
You can close it with IOUtils from https://commons.apache.org/proper/commons-io/
public void readStream(InputStream ins) {
try {
//do some operation with stream
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(ins);
}
}
When closing chained streams, you only need to close the outermost stream. Any errors will be propagated up the chain and be caught.
Refer to Java I/O Streams for details.
To address the issue
However, if flush() throws a runtime exception for some reason, then out.close() will never be called.
This isn't right. After you catch and ignore that exception, execution will pick back up after the catch block and the out.close() statement will be executed.
Your colleague makes a good point about the RuntimeException. If you absolutely need the stream to be closed, you can always try to close each one individually, from the outside in, stopping at the first exception.
In the Java 7 era, try-with-resources is certainly the way to go. As mentioned in several previous answers, the close request propagates from the outermost stream to the innermost stream. So a single close is all that is required.
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
// do something with ois
}
There is however a problem with this pattern. The try-with-resources is not aware of the inner FileInputStream, so if the ObjectInputStream constructor throws an exception, the FileInputStream is never closed (until the garbage collector gets to it). The solution is...
try (FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis)) {
// do something with ois
}
This is not as elegant, but is more robust. Whether this is actually a problem will depend on what exceptions can be thrown during construction of the outer object(s). ObjectInputStream can throw IOException which may well get handled by an application without terminating. Many stream classes only throw unchecked exceptions, which may well result in termination of the application.
you can use try with resources
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
System.out.print("Enter a filename to be read: ");
String file1 = reader.readLine();
System.out.print("Enter a filename to write to: ");
String file2 = reader.readLine();
try(FileInputStream input = new FileInputStream(file1);FileOutputStream output = new FileOutputStream(file2)){
byte[] buffer = new byte[input.available()];
int count = input.available();
input.read(buffer);
for (int i = count-1; i>=0; i--) {
output.write(buffer[i]);
}
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
}
Please go through guidelines before posting any question.
Anyways, I believe, this would be correct way to use Java feature - Try with Resource
private static void copyArray () {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a filename to be read: ");
String file1 = scanner.next();
System.out.print("Enter a filename to write to: ");
String file2 = scanner.next();
scanner.close();
try (FileInputStream input = new FileInputStream(new File(file1)) ;
FileOutputStream output = new FileOutputStream(new File(file2))){
byte[] buffer = new byte[input.available()];
int count = input.available();
input.read(buffer);
for (int i = count-1; i>=0; i--) {
output.write(buffer[i]);
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
}
}
In Java 7 and beyond, there is try with resources which handles Closeable objects.
Reformat your code thusly,
try(JarFile jar = ....; URLClassLoader loader = ....;)
{
// work ...
}
Only classes that implement the Closeable interface will work in this fashion, both of these classes meet this criteria.
Of course there is a way to encapsulate this, it is called a method ! For example, you can create a class IOUtils as the following :
public class IOUtils {
// this class is not meant to be instantiated
private IOUtils() { }
public static void closeQuietly(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) { }
}
}
And then,
JarFile jar = ...;
URLClassLoader loader = ...;
try {
// work ...
} finally {
closeQuietly(jar);
loader.close();
}
As Patrick J Abae II told it, you can also use a try-catch with resources, but you can't always do that, for example if you first create an InputStream in a try-catch, and then create several different kinds of InputStream by encapsulating the first one (ex : encapsulate in a CipherInputStream to decipher the data and then write to a FileOutputStream). Yet, I'm not saying the try-catch with resources is not a useful construct, it is enough in most cases.