Java Reference
In-Depth Information
FileReader reader = null;
try {
reader = new FileReader(filename);
textComponent.read(reader, filename);
} catch (IOException exception) {
System.err.println("Load oops");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
If you later wanted to get the description back from the data model, which happens to be
the file name in this case, you would just ask, like this:
Document document = textComponent.getDocument();
String filename = (String)document.getProperty(Document.StreamDescriptionProperty);
The properties of the Document are simply another key/value lookup table. The key in this
particular case is the class constant Document.StreamDescriptionProperty . If you don't want a
description stored, you pass null as the description argument to the read() method. (The
Document interface will be discussed in more detail later in this chapter.)
Before you can read a file into a text component, you need to create the file to read. This
could be done outside a Java program, or you could use the write() method of JTextComponent
to create the file. The following demonstrates how to use the write() method to write the
contents. For simplicity's sake, it doesn't deal with getting the file name from the Document ,
because this would not be set initially.
FileWriter writer = null;
try {
writer = new FileWriter(filename);
textComponent.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
Search WWH ::




Custom Search