Java Reference
In-Depth Information
static String toHexStr(int value, int fieldWidth)
{
StringBuffer
sb
=
new
StringBuffer(Integer.toHexString(value));
sb.reverse();
int len = sb.length();
for (int i = 0; i < fieldWidth-len; i++)
sb.append('0');
sb.reverse();
return sb.toString();
}
static void writeStr(FileOutputStream fos, String s)
throws IOException
{
for (int i = 0; i < s.length(); i++)
fos.write(s.charAt(i));
}
}
that contains the value of the
line.separator
system property. This constant's
value is output to end the current text line and start a new text line. Because different
platformsprovidedifferentlineseparators(e.g.,newlineonUnix/Linuxorcarriagere-
turn followed by newline on Windows), outputting
LINE_SEPARATOR
ensures max-
imum portability.
DumpFileInHex
next presents its
main()
method, whose first task is to ensure
thatonlyasinglecommand-lineargument(identifyingtheinputfile)hasbeenspecified.
Assumingthatthisisthecase,
main()
nextcreatesthenameoftheoutputfilebyap-
pending
.hex
to the value of the command-line argument.
Continuing,
main()
presentsatry-with-resourcesstatementthatinitiallyopensthe
input file and creates the output file. The try block then employs a while loop to read
eachbytefromtheinputfileandwritethatbyte'shexadecimalrepresentationandliteral
value to the output file, with the help of
toHexStr()
and
writeStr()
methods:
•
toHexStr()
ensuresthatleadingzerosareprependedtoahexadecimalvalue
stringtofitafieldwidth.Forexample,ifahexadecimalvaluemustoccupyex-
actly eight field positions, and if its length is less than 8, leading 0s are pre-