Java Reference
In-Depth Information
The only change to the previous example is in the TryPolylineObjects class. Instead of creating the
variables polygon1 , polygon2 , and polygon3 that hold the references to the objects that are written to
the file, you can use a single variable, polygon :
public class TryPolyLineObjects2 {
public static void main(String[] args) {
// Create an array of coordinate pairs
double[][] coords = { {1., 1.}, {1., 2.}, { 2., 3.},
{-3., 5.}, {-5., 1.}, {0., 0.} };
// Create the path object as before...
// Create the polyline objects and write them to the file
System.out.println("Writing objects to file.");
try (ObjectOutputStream objectOut =
new ObjectOutputStream(
new
BufferedOutputStream(Files.newOutputStream(file)))){
// Create a polyline from the coordinates
PolyLine polygon = new PolyLine(coords);
System.out.println(polygon);
objectOut.writeObject(polygon);
// Write first object
polygon.addPoint(10., 10.);
System.out.println(polygon);
// Add a point
objectOut.writeObject(polygon);
// Write second
object
polygon.addPoint(10., 15.);
System.out.println(polygon);
// Add a point
objectOut.writeObject(polygon);
// Write third object
System.out.println("File written.");
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
// Read the objects from the file and display them as before...
}
}
Directory "TryPolyLineObjects2"
Executing this version of the previous program produces the following output:
Writing objects to file.
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
Search WWH ::




Custom Search