Java Reference
In-Depth Information
// Set the extension for a file path
private Path setFileExtension(Path file, String extension) {
StringBuffer fileName = new StringBuffer(file.getFileName().toString());
if(fileName.indexOf(extension) >= 0) {
return file;
}
int index = fileName.lastIndexOf(".");
if(index < 0) {
// No extension
fileName.append(".").append(extension);
// so append one
}
return file.getParent().resolve(fileName.toString());
}
If there is no extension,
.ske
is appended. If there is an extension, check if it is
.ske
or some other choice of
the user. In either case we leave it as it is. You could have done this easily with inline code, but this method
is more general and is useful later. Add this method definition to the
SketcherFrame
class.
Writing a Sketch to a File
Writing a sketch to a file just involves making use of what you learned about writing objects to a file. You
have already made sure that a
SketcherModel
object is serializable, so you can write the sketch to an
Ob-
jectOutputStream
with the following method in the
SketcherFrame
class:
// Write a sketch to file path file
private boolean saveSketch(Path file) {
try (ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(file)))) {
out.writeObject(theApp.getModel());
// Write the sketch to the stream
} catch(IOException e) {
System.err.println(e);
JOptionPane.showMessageDialog(this,
"Error writing a sketch to " + file,
"File Output Error",
JOptionPane.ERROR_MESSAGE);
return false;
// Serious error - file not written
}
return true;
}
Directory "Sketcher 1 saving a sketch to a file"
The
saveSketch()
method writes the current
SketcherModel
object to the object output stream that you
create from the
Path
object that is passed to it. It returns
true
if the write was successful and
false
if there
was a problem. This enables the calling program to determine whether or not the file was written.
If an error occurs, an exception of type
IOException
is thrown, in which case you write the exception
to the standard error output stream for diagnostic purposes and pop up a dialog indicating that an error has