...
This noncompliant code example reads a byte array and converts it into a String
using the platform's default character encoding. When the default encoding differs from the encoding that was used to produce the byte array, the resulting String
is likely to be incorrect. Undefined behavior can occur when some of the input lacks a valid character representation in the default encoding.
Code Block | ||
---|---|---|
| ||
try { FileInputStream fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); int bytesRead = 0; byte[] data = new byte[1024]; bytesRead = dis.readFully(data); if (bytesRead > 0) { String result = new String(data); } catch (IOException x) { // handle error } |
Compliant Solution
This compliant solution explicitly specifies the intended character encoding by passing it as the second argument to the String
constructor (e.g. the string encoding
in this example).
Code Block | ||
---|---|---|
| ||
String encoding = "SomeEncoding" // for example, "UTF-16LE" try { FileInputStream fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); int bytesRead = 0; byte[] data = new byte[1024]; bytesRead = dis.readFully(data); if (bytesRead > 0) { String encoding = "SomeEncoding"; // for example, "UTF-16LE" String result = new String(data, encoding); } catch (IOException x) { // handle error } |
Exceptions
FIO03-EX1: An explicit character encoding may be omitted on the receiving side when the data was created produced by another a Java application that both uses the same platform and also uses the default character encoding.
...