File Viewer, Part 1
I often find it useful to be able to open an arbitrary file and interpret it in an arbitrary fashion. Most commonly I want to view a file as text, but occasionally it’s useful to interpret it as hexadecimal integers, IEEE 754 floating-point data, or something else. In this book, I’m going to develop a program that lets you open any file and view its contents in a variety of different ways. In each chapter, I’ll add a piece to the program until it’s fully functional. Since this is only the beginning of the program, it’s important to keep the code as general and adaptable as possible.
Example 4.3 reads a series of filenames from the
command line in the main() method. Each filename
is passed to a method that opens the file. The file’s data is
read and printed on System.out. Exactly how the
data is printed on System.out is determined by a
command-line switch. If the user selects ASCII format
(-a), then the data will be assumed to be ASCII
(more properly, ISO Latin-1) text and printed as
chars. If the user selects
decimal
dump (-d), then each byte should be printed as
unsigned decimal numbers between
and 255, 16 to a line. For example:
000 234 127 034 234 234 000 000 000 002 004 070 000 234 127 098
Leading zeros
are used to maintain a constant width for the printed byte values and
for each line. A simple selection algorithm is used to determine how
many leading zeros to attach to each number. For hex dump format
(-h), each byte should be printed as two hexadecimal ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access