Java Reference
In-Depth Information
Example 3−3: FileViewer.java (continued)
// Figure out the directory, from filename or current dir, if necessary
if (directory == null) {
File f;
if ((filename != null) && (f = new File(filename)).isAbsolute()) {
directory = f.getParent();
filename = f.getName();
}
else directory = System.getProperty("user.dir");
}
this.directory = directory; // Remember the directory, for FileDialog
setFile(directory, filename); // Now load and display the file
}
/**
* Load and display the specified file from the specified directory
**/
public void setFile(String directory, String filename) {
if ((filename == null) || (filename.length() == 0)) return;
File f;
FileReader in = null;
// Read and display the file contents. Since we're reading text, we
// use a FileReader instead of a FileInputStream.
try {
f = new File(directory, filename); // Create a file object
in = new FileReader(f); // And a char stream to read it
char[] buffer = new char[4096]; // Read 4K characters at a time
int len; // How many chars read each time
textarea.setText(""); // Clear the text area
while((len = in.read(buffer)) != -1) { // Read a batch of chars
String s = new String(buffer, 0, len); // Convert to a string
textarea.append(s);
// And display them
}
this.setTitle("FileViewer: " + filename); // Set the window title
textarea.setCaretPosition(0);
// Go to start of file
}
// Display messages if something goes wrong
catch (IOException e) {
textarea.setText(e.getClass().getName() + ": " + e.getMessage());
this.setTitle("FileViewer: " + filename + ": I/O Exception");
}
// Always be sure to close the input stream!
finally { try { if (in!=null) in.close(); } catch (IOException e) {} }
}
/**
* Handle button clicks
**/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("open")) { // If user clicked "Open" button
// Create a file dialog box to prompt for a new file to display
FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
f.setDirectory(directory);
// Set the default directory
// Display the dialog and wait for the user's response
f.show();
Search WWH ::




Custom Search