1

I wrote the below code snippets and i'm expecting the output to be Açılış Tarih/Saati: but instead i'm getting Açılış Tarih/Saati: The code is as follows.

public class ResourceBundleTest {

public static void main(String[] args) {            
        try{
        String turkey = "A\u00e7\u0131l\u0131\u015f Tarih/Saati:";
        System.out.println(new String(turkey.getBytes("UTF-8")));
        }
        catch(Exception e)
        {
            System.out.println("hello");
        }
    }

}

Please help me how can i get rid of this issue.

4

2 回答 2

4

This code is basically broken:

new String(turkey.getBytes("UTF-8"))

That:

  • Starts with a string.
  • Encodes the text as UTF-8.
  • Decodes that binary data using the platform default encoding.

It's like saving an image as a PNG and then trying to load it as a JPEG.

You can try:

System.out.println(turkey);

... if that doesn't show up as you want it to, the problem is probably just that your console doesn't support those characters. Trying to change the encoding won't help at all - the best it could do (if you were really lucky) is to get back to the original string. More likely (and it seems this is the case with your output) is that the platform default encoding isn't UTF-8, so you're losing data.

于 2013-06-27T18:53:44.120 回答
1

In turkey.getBytes("UTF-8") you explicitly create a byte-array containing the String contents encoded in UTF-8. However the contructor String(byte[]) decodes, according to its documentation, this byte sequence using the system's default encoding. Which may not be UTF-8.

Why don't you just write System.out.println(turkey), though? What's the point of encoding the String in UTF-8 and then decoding it before printing it?

于 2013-06-27T18:54:47.023 回答