12.7. Concepts SummaryIn this chapter we have learned about handling exceptions, reading and writing files, reading from the Internet, using import statements, using while loops, manipulating String objects, and using ArrayList objects (dynamic arrays). 12.7.1. ExceptionsAn exception occurs when something goes wrong. Exception handling shouldn't be used to handle normal execution of a program, but it is used to handle exceptional events. For example if you try to read from a file and the file doesn't exist, you will get a FileNotFoundException. If you try to write to a file and the disk is full, you will get an IOException. If you try to invoke a method on a object reference that is null, you will get a NullPointerException. Each of these exceptions inherits from java.lang.Exception, and each is an object. Every exception knows how to print the call stack (using the method printStackTrace()) which is helpful in figuring out where the exception occurred and how it got there. There are two kinds of exceptions: checked and unchecked. The programmer must do something to handle checked exceptions. You can either catch exceptions or throw them. The programmer is not required to handle unchecked exceptions such as NullPointerException or ArrayIndexOutOfBoundsException. To catch an exception use: try { // statements that can cause exceptions } catch (Exception ex) { // what to do if an exception happens } finally { // what to do no matter what happens above } The finally block is optional. If a finally block is present it will be executed both if an exception occurs and if an exception does not occur. You can have more than one catch block. All Exception objects inherit from java.lang.Exception. When you catch an Exception object you will also catch all objects that inherit from the type you specified. 12.7.2. Reading and Writing FilesThe classes that handle reading and writing files are in the package java.io. Each class in the package is responsible for one task and the classes can be combined in different ways to solve different problems. Classes that work with character data are Reader and Writer classes. Classes that work with binary data are Stream classes. A stream is a series of bits. To read files we created a BufferedReader using a FileReader to buffer the data from the disk after it is read from the file. We used the readLine() method of BufferedReader to loop reading from the file until the returned String was null. Reading from a file can cause checked exceptions so we enclosed the code in a try block and added catch blocks to catch the exceptions. To write files we created a BufferedWriter using a FileWriter to buffer the data in before writing it to the file. We used the write method to write String objects to the file and we used the newLine() method to force a new line in the file. Writing to a file can cause checked exceptions so we enclosed the code in a try block and added catch blocks to catch the exceptions. We also used the File class to get a list of the files in a directory. 12.7.3. Reading from the InternetTo create a program that reads directly from the Internet we used the URL class from the java.net package. We created a URL object from a string representation of a URL. Then we used the openStream() method on the URL object to get back a java.io.InputStream object which knows how to read from a stream of bytes. We used the InputStream object to create a java.io.InputStreamReader object which knows how to turn the bytes into characters. We created a java.io. BufferedReader object from the InputStreamReader to handle the buffering of the data in memory. Then we were able to use the readLine() method of BufferedReader to read from the network. 12.7.4. Import StatementsWhenever we use classes from a package other than java.lang we have to specify either the full name of the class or use an import statement before the class declaration. The full name of a class is the package name followed by a '.' and then the class name. The full name of the BufferedReader class is java.io.Buffered-Reader. If we want to refer to this in our code as just BufferedReader we need an import statement before the class declaration. We can import this as: import java.io.BufferedReader; which imports just that class. Or we can use: import java.io.*; which allows us to use all the classes in that package. It doesn't include any code, it just tells the compiler where to look for the class. If you are using more than one class from a package, this second way is easier. 12.7.5. While LoopsEven though for loops and while loops are the same as far as the computer is concerned, people use them in different ways. Use a for loop when you know how many times the loop will execute and a while loop when you want to loop as long as a boolean test is true. We used a while loop to read lines from a file until the line read was null, which indicates that we have reached the end of the file. // Loop while there is more data while((line = reader.readLine()) != null) { // print the current line System.out.println(line); } Methods SummaryString methods Strings are sequences of characters. The first character is at index 0. You can get the length of a string using the method length(). Here are the other methods we covered:
ArrayList MethodsAn ArrayList is a dynamic array (an array that can grow or shrink as needed). It is in the package java.util. It implements the java.util.List interface and thus an object of the class ArrayList can be referred to by a variable declared as type List. The methods that we covered are:
File MethodsWe have only covered one method of the java.io.File class. The method list() returns an array of String objects which are the names of all the items in the directory represented by the File object. Random MethodsWe have covered two methods of the java.util.Random class. The method nextdouble() will return a double between 0 and 1.0 inclusive. The method nextInt(int num) will return an integer between 0 (inclusive) and num exclusive. |