Sorry

Simple utility applications can be very helpful to Java developers. For example, you might need an application that generates a hexadecimal listing of a binary file. In this post, I present command-line-based and GUI-based versions of this utility application.

Command-line-based hexadecimal file dump

Q: Can you provide me with a command-line-based Java application that generates a hexadecimal listing of a binary file?

A: Listing 1 presents the contents of a HexDump application that reads the contents of a specified file and dumps this file's hexadecimal listing to standard output.

Listing 1. A command-line-based utility application for dumping a file's contents in hexadecimal to standard output

Listing 1's main() method uses simple logic to generate a hexadecimal listing. It relies on an instance of the java.lang.StringBuffer class to store the literal characters that appear to the right of the hexadecimal values.

Compile Listing 1 (javac HexDump.java) and run this application on the resulting classfile (java HexDump HexDump.class). You should observe the following output:

Listing 2's constructor creates a GUI and loads a file when specified by a command-line argument, assigning its hexadecimal listing to the scrollable text area. (I'm not worried about the performance implications of loading a file on the event-handling thread in this application.)

The text area's purpose is to present a read-only listing, and so it shouldn't be editable. Although passing false to setEnabled() accomplishes this task, the resulting listing is too dim to read. You can also make a text area read-only by passing false to setFocusable().

The read() method reads the file and transforms its contents into a hexadecimal listing. I use a java.util.Formatter instance to store the entire listing. I use a StringBuffer instance to temporarily store a line's literal characters (or periods).