File Viewer, Part 3

In Chapter 4, I introduced a FileDumper program that could print the raw bytes of a file in ASCII, hexadecimal, or decimal. In this chapter, I’m going to expand that program so that it can interpret the file as containing binary numbers of varying widths. In particular I’m going to make it possible to dump a file as shorts, unsigned shorts, ints, longs, floats, and doubles. Integer types may be either big-endian or little-endian. The main class, FileDumper3, is shown in Example 7.10. As in Chapter 4, this program reads a series of filenames and arguments from the command line in the main() method. Each filename is passed to a method that opens a file input stream from the file. Depending on the command-line arguments, a particular subclass of DumpFilter from Chapter 6 is selected and chained to the input stream. Finally, the StreamCopier.copy() method pours data from the input stream onto System.out.

Example 7-10. The FileDumper3 Class

import*; import*; public class FileDumper3 { public static final int ASC = 0; public static final int DEC = 1; public static final int HEX = 2; public static final int SHORT = 3; public static final int INT = 4; public static final int LONG = 5; public static final int FLOAT = 6; public static final int DOUBLE = 7; public static void main(String[] args) { if (args.length < 1) { System.err.println( "Usage: java FileDumper3 [-ahdsilfx] [-little] file1 file2..."); } boolean bigEndian = true; int firstFile = ...

Get Java I/O now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.