Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 11 Exceptions and Assertions

Try-with-Resources

It is a fairly common mistake by Java programmers to forget releasing resources, even in the finally block. Also, if you’re dealing with multiple resources, it is tedious to remember to call the close() method in the finally block. Java 7 introduced a feature named try-with-resources to help make your life easier. Listing 11-9 makes use of this feature; it is an improved version of Listing 11-8.

Listing 11-9.  TryWithResources1.java

import java.util.*;

class TryWithResources1 {

        public static void main(String [] args) {

                System.out.println("Type an integer in the console: ");

                try(Scanner consoleScanner = new Scanner(System.in)) {

System.out.println("You typed the integer value: " + consoleScanner.nextInt());

                } catch(Exception e) {

                        // catch all other exceptions here ...

System.out.println("Error: Encountered an exception and could not read an integer from the console... ");

System.out.println("Exiting the program - restart and try the program again!");

                }

        }

}

The behavior will be similar to that of the program in Listing 11-7, so we’re not running the program and showing the sample output again.

Make sure you take a closer look at the syntax for try-with-resources block.

try(Scanner consoleScanner = new Scanner(System.in)) {

In this statement, you have acquired the resources inside the parenthesis after the try keyword, but before the try block. Also, in the example, you don’t provide the finally block. The Java compiler will internally translate this try-with-resources block into a try-finally block (of course, the compiler will retain the catch blocks you provide). You can acquire multiple resources in the try-with-resources block; such resource acquisition statements should be separated by semicolons.

Can you provide try-with-resources statements without any explicit catch or finally blocks? Yes! Remember that a try block can be associated with a catch block, finally block, or both. A try-with-resources statement block gets expanded internally into a try-finally block. So, you can provide a try-with-resources statement without explicit catch or finally blocks. Listing 11-10 uses a try-with-resources statement without any explicit catch or finally blocks.

Listing 11-10.  TryWithResources2.java

import java.util.*;

class TryWithResources2 {

        public static void main(String [] args) {

                System.out.println("Type an integer in the console: ");

                try(Scanner consoleScanner = new Scanner(System.in)) {

System.out.println("You typed the integer value: " + consoleScanner.nextInt());

                }

        }

}

332

Chapter 11 Exceptions and Assertions

Although it is possible to create a try-with-resources statement without any explicit catch or finally, it doesn’t mean you should do so! For example, since this code does not have a catch block, if you type some invalid input, the program will crash.

D:\> java TryWithResources1 Type an integer in the console: ten

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909)

at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119)

at TryWithResources1.main(TryWithResources1.java:7)

So, the benefit of a try-with-resources statement is that it simplifies your life by not having to provide finally blocks explicitly. However, you still need to provide necessary catch blocks.

Note that for a resource to be usable with a try-with-resources statement, the class of that resource must implement the java.lang.AutoCloseable interface. This interface declares one single method named close(). You already know that the try-with-resources feature was added in Java 7. This AutoCloseable interface was also introduced in Java 7, and the interface is made of the base interface of the Closeable interface. This is to make sure

that the existing resource classes work seamlessly with a try-with-resources statement. In other words, you can use all old stream classes with try-with-resources because they implement the AutoCloseable interface.

Closing Multiple Resources

You can use more than one resource in a try-with-resources statement. Here is a code snippet for creating a zip file from a given text file that makes use of a try-with-resources statement:

//buffer is the temporary byte buffer used for copying data from one stream to another stream byte [] buffer = new byte[1024];

//these stream constructors can throw FileNotFoundException

try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName)); FileInputStream fileIn = new FileInputStream(fileName)) { zipFile.putNextEntry(new ZipEntry(fileName));         // putNextEntry can throw

// IOException

        int lenRead = 0; // the variable to keep track of number of bytes sucessfully read

        // copy the contents of the input file into the zip file

        while((lenRead = fileIn.read(buffer)) > 0) {         // read can throw IOException

                zipFile.write(buffer, 0, lenRead);         // write can throw IOException

}

//the streams will be closed automatically because they are within try-with-

//resources statement

}

In this code, the buffer is a byte array. This array is temporary storage useful for copying raw data from one stream to another stream. In the try-with-resources statement, you open two streams: ZipOutputStream for writing to the zip file and FileInputStream for reading in the text file. (Note: API support for zip (and jar) files is available in java.util.zip library.) You want to read the input text file, zip it, and put that entry in the zip file. For putting a

333

Chapter 11 Exceptions and Assertions

file/directory entry into the zip file, the ZipOutputStream class provides a method named putNextEntry(), which takes a ZipEntry object as an argument. The statement zipFile.putNextEntry(new ZipEntry(fileName)); puts a file entry named fileName into the zipFile.

For reading the contents of the text file, you use the read() method in the FileInputStream class. The read() method takes the buffer array as the argument. The amount of data to read per iteration (i.e., “data chunk size” to read) is given by the size of the passed array; it is 1024 bytes in this code. The read() method returns the number of bytes it read, and if there is no more data to read, it returns –1. The while loop checks if read succeeded (using the > 0 condition) before writing it to the zip file.

For writing data to the zip file, you use the write() method in the ZipOutputStream class. The write() method takes three arguments: the first argument is the data buffer; the second argument is start offset in the data buffer (which is 0 because you always read from the start of the buffer); and the third is the number of bytes to be written.

Now we come to the main discussion. Note how you open two resources in the try block and these two resource acquisition statements are separated by semicolons. You do not have an explicit finally block to release the resources because the compiler will automatically insert calls to the close methods for these two streams in the finally block(s).

Listing 11-11 is the complete program that makes use of this code segment to illustrate the use of try-with- resources statement for auto-closing multiple streams.

Listing 11-11.  ZipTextFile.java

import java.util.*; import java.util.zip.*; import java.io.*;

//class ZipTextFile takes the name of a text file as input and creates a zip file

//after compressing that text file.

class ZipTextFile {

        public static final int CHUNK = 1024; // to help copy chunks of 1KB

        public static void main(String []args) {

                if(args.length == 0) {

System.out.println("Pass the name of the file in the current directory to be zipped as an argument");

                        System.exit(-1);

                }

                String fileName = args[0];

                // name of the zip file is the input file name with the suffix ".zip"

                String zipFileName = fileName + ".zip";

                byte [] buffer = new byte[CHUNK];

                // these constructors can throw FileNotFoundException

try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName)); FileInputStream fileIn = new FileInputStream(fileName)) {

                        // putNextEntry can throw IOException zipFile.putNextEntry(new ZipEntry(fileName));

                        int lenRead = 0; // variable to keep track of number of bytes // successfully read

                        // copy the contents of the input file into the zip file

                        while((lenRead = fileIn.read(buffer)) > 0) {

                                // both read and write methods can throw IOException zipFile.write (buffer, 0, lenRead);

                }

334

Chapter 11 Exceptions and Assertions

                        // the streams will be closed automatically because they are // within try-with-resources statement

                }

                // this can result in multiple exceptions thrown from the try block;

// use "suppressed exceptions" to get the exceptions that were suppressed!

                catch(Exception e) {

                        System.out.println("The caught exception is: " + e);

                        System.out.print("The suppressed exceptions are: ");

                        for(Throwable suppressed : e.getSuppressed()) {

                                System.out.println(suppressed);

                        }

                }

        }

}

We’ve already discussed the try-with-resources block part. What we have not discussed is suppressed exceptions. In a try-with-resources statement, there might be more than one exception that could get thrown; for example,

one within the try block, one within the catch block, and another one within the finally block. However, only one exception can be caught, so the other exception(s) will be listed as suppressed exceptions. From a given exception object, you can use the method getSuppressed() to get the list of suppressed exceptions.

Points to Remember

Here are some interesting points about try-with-resources statement that will help you in the OCPJP 7 exam:

You cannot assign to the resource variables declared in the try-with-resources within the body of the try-with-resources statement. This is to make sure that the same resources acquired in the try-with-resources header are released in the finally block.

It is a common mistake to close a resource explicitly inside the try-with-resources statement. Remember that try-with-resources expands to calling the close() method in the finally block, so the expanded code will have a double call to the close() method. Consider the following code:

try(Scanner consoleScanner = new Scanner(System.in)) {

System.out.println("You typed the integer value: " + consoleScanner.nextInt()); consoleScanner.close();

//explicit call to close() method - remember that try-with-resources

//statement will also expand to calling close() in finally method;

      // hence this will result in call to close() method in Scanner twice!

}

The documentation of the close() method in the Scanner class says that if the scanner object is already closed, then invoking the method again will have no effect. So, you are safe in this case. However, in general, you cannot expect all the resources to have implemented a close() method that is safe to call twice. So, it is a bad practice to explicitly call the close() method inside a try-with-resource statement.

335

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]