为什么这个Java程序给Eclipse不正确的结果和从终端运行时的正确结果? [英] Why is this Java program gives incorrect results on Eclipse and correct results when run from terminal?

查看:196
本文介绍了为什么这个Java程序给Eclipse不正确的结果和从终端运行时的正确结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序。

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()));

    }
}

java HelloWorld

我得到正确编码,形状文本。默认编码为 MacRoman

I get properly encoded, shaped text. Default encoding was MacRoman.

现在,当我从Eclipse执行相同的代码,我看到不正确的文本打印到控制台。

Now when I execute the same code from Eclipse, I see incorrect text getting printed to the console.

当我将Eclipse的文件编码选项更改为 UTF-8 时,它在Eclipse中输出正确的结果。

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

我想知道为什么会发生这种情况?理想情况下,文件编码选项不应该影响这个代码,因为这里我明确使用UTF-8。

I am wondering why this happens? Ideally, file encoding options should not have affected this code because here I am using UTF-8 explicitly.

有什么想法为什么会发生这种情况?

Any idea why this is happening?

我使用的是Java 1.6(Sun JDK),Mac OSx 10.7 。

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

推荐答案

您需要指定在创建字符串时要使用的编码:

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

new String(encoded.array(), charset)

否则将使用默认字符集。

otherwise it will use the default charset.

这篇关于为什么这个Java程序给Eclipse不正确的结果和从终端运行时的正确结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆