5
Hello,
When creating a string in a Java class (for example: String t = "Ola Java!"
), it seems that the compiler is choosing the 'wrong' encounter to interpret the bytes that are in the source and generate the String (the 'right' encounter should be UTF-8
, which is the Encode I’m using in the sources).
To illustrate the error, I ran the following test:
String t = "ã";
log.debug("t: " + t);
log.debug("t.length(): " + t.length());
log.debug("t.getBytes().length: " + t.getBytes().length);
log.debug("t.getBytes(utf-8).length: " + t.getBytes("utf-8").length);
log.debug("t.getBytes(UTF-8).length: " + t.getBytes("UTF-8").length);
log.debug("t.getBytes(ISO-8859-1).length: " + t.getBytes("ISO-8859-1").length);
(the log mechanism I use is the commons-logging
with log4j
support, but to do the same using the System.out
)
The result was as follows:
t: ã
t.length(): 2
t.getBytes().length: 4
t.getBytes(utf-8).length: 4
t.getBytes(UTF-8).length: 4
t.getBytes(ISO-8859-1).length: 2
The first line could be explained by some conversion problem when converting the string at the time of writing the log file.
But the other lines make the problem clear.
On the second line (t.length()
) to see that the String was created with two characters, and not one, already showing that in the creation of the string the two bytes that represent the character in utf-8
have been treated as two characters (in some other ISO-8859-1 format).
I’m looking for some way to force I find in the interpretation of a static string by the compiler, but I don’t think it’s a good way... is there any way to do this? Or to indicate to the compiler which Encode should be used when interpreting static strings in sources ?
Ok, I solved the problem. There is an option in the compiler to force the Encode that it handles the files. The option is: -encoding (there is also an ant javac task). Placing the utf-8 valve worked. By the way, the compiler uses the default OS for its default, and not the default adopts in the classes (UTF-8)... nothing like putting the written question to have a new view of it!
– Roberto Barra
Add your solution as the answer to the question...
– AndersonBS
Okay, I’ll do it later. At the moment I’m being shadowed to go to a barbecue!...
– Roberto Barra