Exercise focused on working with input and output.
Modify the LabeledPolygon.Builder class to implement the PolygonReadable interface.
Modify the LabeledPolygon class to implement the PolygonWritable interface.
-
The
read(InputStream)method takes an open input containing named vertices, reads the vertices, and adds them to the existing vertices of the polygon. For any input/output error or input data format error, the method must atomically fail and throw anIOException. (atomically = loading all or nothing) The input data format is as follows:- The input is text.
- Each vertex is on one line.
- Each line is in the format "x y vertex name", i.e. first the coordinates of the vertex separated by a space and then the name of the vertex (the name can contain spaces). See, for example, the file polygon-ok.txt.
-
The
write(OutputStream)method writes vertices to a given output stream. The output format is the same as for the previous method. -
The
write(File)andread(File)methods will work the same as before, however, they will work with the file instead of the I/O stream. Avoid code repetition! -
Create a
writeJson(OutputStream os)method that will write a map in JSON format to the output stream.- Use external library gson.
For maven, you need to add a dependency to the
pom.xmlfile in the<dependencies>section. - Read the Gson class documentation.
- According to documentation use the so-called pretty print.
- An object of type Gson can be reused, so you only need to create it once.
- Use external library gson.
For maven, you need to add a dependency to the
-
Edit the
Democlass as follows:- The class creates
LabeledPolygonfrom the filepolygon-ok.txt. - The polygon will also contain a vertex named
vertex xwith coordinates[123, 456]. - Write the output to the output stream
System.outin JSON format. - To check that the output stream is still open then print
Hello World!.
- The class creates
-
Running the
Drawclass loads polygon-ok.txt and draws on the screen.
- Only close streams/files that you have opened.
- Use try with resources.
- Study the methods
Writer#flush(),Reader#ready(). - Creating a file:
new File("soubor.txt"). Demo.maincan throwIOException.- Instead of
\n, use the universal line break separator,System.lineSeparator(). - The tests create a
polygon-out.txtfile.