Wiki Markup |
---|
Every Java platform has a default character encoding. The available encodings are listed in \[[Encodings 06|AA. Java References#Encodings 06]\]. The default encoding is used when a character is converted to a sequence of bytes and _vice versa_. If characters are converted into an array of bytes to be sent as output, transmitted across some medium, input and converted back into characters, then the same encoding must be used on both sides of the conversation. |
...
Noncompliant Code Example
In this This noncompliant code example , reads a byte array is read and converted converts it into a String
using the default character encoding for the platform. If this is not the same encoding as the one that was used to produce the byte array, the resulting String
is likely to be incomprehensible because some of the bytes may not have valid character representations in the default encoding.
Code Block | ||
---|---|---|
| ||
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);
}
|
...
In this compliant solution, the encoding is explicitly specified by using passing the String
string encoding
as the second parameter argument of the String
constructor.
Code Block | ||
---|---|---|
| ||
String encoding = "SomeEncoding" // for example, "UTF-16LE" 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, encoding); } |
...