...
Compliant Solution (ByteBuffer)
This compliant solution uses methods provided by class {{Wiki Markup ByteBuffer}} (see \ [[API 2006|AA. References#API 06] \] [{{ByteBuffer}}|http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html]) to correctly extract an {{int}} from the original input value. It wraps the input byte array with a {{ByteBuffer}}, sets the byte order to little-endian, and extracts the {{int}}. The result is stored in the integer {{serialNumber}}. Class {{ByteBuffer}} provides analogous get and put methods for other numeric types.
| Code Block | ||
|---|---|---|
| ||
try {
DataInputStream dis = null;
try {
dis = new DataInputStream( new FileInputStream("data"));
byte[] buffer = new byte[4];
int bytesRead = dis.read(buffer); // Bytes are read into buffer
if (bytesRead != 4) {
throw new IOException("Unexpected End of Stream");
}
int serialNumber =
ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException x) {
// handle error
}
}
}
} catch (IOException x) {
// handle error
}
|
...
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f6b365e5-ba0e-41c4-8075-8483c9636b91"><ac:plain-text-body><![CDATA [ [[API 2006AA. References#API 06] ] | [Class | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4e141b41-1e81-40aa-b28f-db8ab428b2b4"><ac:plain-text-body><! [CDATA[ [[Cohen 1981AA. References#Cohen 81]] | On Holy Wars and a Plea for Peace | ]]></ac:plain-text-body></ac:structured-macro> | <ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2787e403-3917-4086-9ddc-e12208b32460"><ac:plain-text-body><![CDATA[ |
[ [Harold 1997AA. References#Harold 97] ] | Chapter 2, Primitive Data Types, Cross-Platform Issues ]]></ac:plain-text-body></ac:structured-macro> |
...
FIO11-J. Do not attempt to read raw binary data as character data 12. Input Output (FIO)