...
The read methods (readByte, readShort, readInt, readLong, readFloat and readDouble) and the corresponding write methods defined by class java.io.DataInputStream operate only on big-endian data. Use of these methods while interoperating with traditional languages, such as C or C++, is insecure because such languages lack any guarantees about endianness. This noncompliant code example shows such a discrepancy.
| Code Block | ||
|---|---|---|
| ||
try { DataInputStream dis = null; try { dis = new DataInputStream( new FileInputStream("data")); // Little-endian data might be read as big-endian int serialNumber = dis.readInt(); } finally { if (dis != null) { dis.close(); } } catch (IOException x) { // handle error } } |
Compliant Solution (Use ByteBuffer)
| Wiki Markup |
|---|
This compliant solution uses methods provided by class {{ByteBuffer}} (see \[[API 2006|AA. Bibliography#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}}. |
| 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) { dis.close(); } } } catch (IOException x) { // handle error } |
Class ByteBuffer provides analogous get and put methods for the other numeric types.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b7e3cc13416ad767-6446dcd2-4a29494e-b7f4b715-569465488994af1cb7ea61a6"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | Class [ByteBuffer | http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html]: Methods | http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html]: method | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5451d63a8a3e1e0b-b86e3c76-4a1e4ac2-8c238dea-2793e2886aeec8dddb0da270"><ac:plain-text-body><![CDATA[ | [[Cohen 1981 | AA. Bibliography#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="46ba409bc0e4d19c-33bcac40-4bd54333-a5c39003-1a0b2fa93602b9392dd9e91d"><ac:plain-text-body><![CDATA[ | [[Harold 1997 | AA. Bibliography#Harold 97]] | Chapter 2: "Primitive Data Types, Cross Platform issues" | ]]></ac:plain-text-body></ac:structured-macro> |
...