Why does this Java program give incorrect results in Eclipse and correct the results when it starts from the terminal?

Consider the following program.

import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; public class HelloWorld { public static void main(String[] args) { System.out.println(Charset.defaultCharset()); char[] array = new char[3]; array[0] = '\u0905'; array[1] = '\u0905'; array[2] = '\u0905'; CharBuffer charBuffer = CharBuffer.wrap(array); Charset utf8 = Charset.forName("UTF-8"); ByteBuffer encoded = utf8.encode(charBuffer); System.out.println(new String(encoded.array())); } } 

When I do this using a terminal,

 java HelloWorld 

I get correctly encoded, formatted text. The default encoding was MacRoman .

Now, when I run the same code from Eclipse, I see the wrong text printed on the console.

Eclipse console showing scrambled text

When I change the encoding option of an Eclipse file to UTF-8 , it prints the correct results in Eclipse.

I wonder why this is happening? Ideally, file encoding settings should not have influenced this code, because here I use UTF-8 explicitly.

Any idea why this is happening?

I am using Java 1.6 (Sun JDK), Mac OSx 10.7.

+4
source share
5 answers

You need to specify which encoding you want to use when creating the string:

 new String(encoded.array(), charset) 

otherwise it will use the default encoding.

+3
source

Make sure that the console you use to display the output is also encoded in UTF-8. For example, in Eclipse, you need to go to Run Configuration> Common to do this.

enter image description here

+2
source
 System.out.println("\u0905\u0905\u0905"); 

will be direct use.

And for the constructor of String there is no encoding, by default the standard encoding is used by default.

 new String(encoded.array(), "UTF-8") 
+1
source

This is because Eclipse uses ANSI encoding by default, not UFT-8. If you use a different encoding than what your IDE uses, you will get unreadable results.

0
source

you need to change the console launch configuration.

  • click "Run"
  • click β€œRun Configurations” and then click the β€œNormal” tab
  • change encoding to utf enter image description here
0
source

Source: https://habr.com/ru/post/1486878/


All Articles