Exercises

  • Exercise 6-1. The FileCopy3 program in Example 6-4 omits exception-handling and channel-closing code for simplicity. Make this program more robust by adding that code, using Example 6-2, or other examples, as a model.

  • Exercise 6-2. The ChannelToWriter.copy( ) method of Example 6-5 reads bytes from a ReadableByteChannel, decodes them using a CharsetDecoder, and writes the resulting characters to a Writer. Write a method that does the reverse: reads characters from a Reader, encodes them using a CharsetEncoder, and writes the resulting bytes to a WritableByteChannel. Use a low-level encoding loop based on the decoding loop of Example 6-5.

  • Exercise 6-3. The BGrep class of Example 6-3 is a block-oriented rather than line-oriented regular-expression matcher. Modify the program to search a line at a time, rather than searching an entire file at a time. The easiest way to do this is probably to abandon the java.nio package and use java.io.BufferedReader to read lines. An alternative is to use the scan( ) method of the ChannelTokenizer class (see Examples Example 6-8 and Example 2-8).

  • Exercise 6-4. The HttpGet program in Example 6-9 discards HTTP headers. Modify it with a -h command-line option, which, when present, causes it to print out the headers it receives.

  • Exercise 6-5. A shortcoming of the HttpGet program of Example 6-9 is that it does not understand and follow HTTP redirects. Some servers use these HTTP response codes to distribute load, and HttpGet is unable to download ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.