Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added finally-close clause to code samples

...

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
bgColor#FFCCCC
FileInputStream fis = null;
try {
  FileInputStream fis = new FileInputStream("SomeFile");
  DataInputStream dis = new DataInputStream(fis);
  byte[] data = new byte[1024];
  dis.readFully(data);
  String result = new String(data);
} catch (IOException x) {
  // handle error
} finally {
  if (fis != null) {
    try {
      fis.close();
    } catch (IOException x) {
      // Forward to handler
    }
  }
}

Compliant Solution

This compliant solution explicitly specifies the intended character encoding in the second argument to the String constructor.

Code Block
bgColor#ccccff

FileInputStream fis = null;
try {
  FileInputStream fis = new FileInputStream("SomeFile");
  DataInputStream dis = new DataInputStream(fis);
  byte[] data = new byte[1024];
  dis.readFully(data);
  String encoding = "SomeEncoding"; // for example, "UTF-16LE"
  String result = new String(data, encoding);
} catch (IOException x) {
  // handle error
} finally {
  if (fis != null) {
    try {
      fis.close();
    } catch (IOException x) {
      // Forward to handler
    }
  }
}

Exceptions

IDS13-EX0: An explicit character encoding may be omitted on the receiving side when the data was produced by a Java application that uses the same platform and default character encoding and the data is communicated over a secure communication channel (see MSC00-J. Use SSLSockets rather than Sockets for secure data exchange).

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8856b569e4be5b46-699f5060-4ec34e22-a5c6ba9f-de9796b9e0d64690abdfaa48"><ac:plain-text-body><![CDATA[

[[Encodings 2006

AA. Bibliography#Encodings 06]]

]]></ac:plain-text-body></ac:structured-macro>

...