Java Reference
In-Depth Information
out.writeObject(sizeComboBox. getSelectedItem()) ;
out.writeObject(fontComboBox. getSelectedItem()) ;
out .writeObject(textArea . getText()) ;
}
catch (Exception exception) {
}
}
}
} );
}
}
Note that we stored the values for the bold and italic check boxes as boolean ,thatis,
we used the writeBoolean method to write them to the file. We stored the values for the
combo boxes and the text as objects, that is, we used the writeObject method to store
them. When reading from the file, we used the readBoolean method to read the two Boolean
values. Similarly, we used the readObject method multiple times to read the objects from
the file. Note that the method readObject returns an object. This object may have to be
cast to the appropriate type. For example, the statement (String)in.readObject() reads
an object from the file and converts it to a string. If the object is not of type String ,then
a ClassCastException will be generated.
Note that the information must be read from the file in the same order that it was
written to the file. Go ahead and run the program. You will see that the formatting is now
preserved. If we open a file that is created by the program using a text editor, we will see
that the file is no longer text and it now contains strange symbols that represent binary
data.
13.4 Summary
The chapter shows how to create both text and binary files. It also discusses the topic
of checked and unchecked exceptions. While Java forces us to handle checked exceptions,
unchecked exceptions do not need to be handled. For example, code can access an element of
an array without worrying about an ArrayIndexOutOfBounds exception. Conversely, every
time we open a file for reading or writing, we need to add code that checks for exceptions.
The reason is that something can go wrong (i.e., the file cannot be written) and Java forces
us to handle this exception case.
13.5 Syntax
￿ void m() throws Exception
If an exception is generated in the m method and the
exception is not handled, then the exception is forwarded to the method that called
the m method. This syntax is used primarily when there is a checked exception that
needs to be addressed. If an unhandled exception is generated from the main method,
then the program crashes.
Prints the error on the screen in red.
￿
System.err.print("error ...");
 
Search WWH ::




Custom Search