1

我有一个非常简单的代码:

package org;

import java.nio.charset.Charset;

public class Test
{
  public static void main(String[] args)
  {
    System.out.println(Charset.defaultCharset());
  }
}

我在 Windows7 RUS JRE7 上运行它。

当我使用“Debug”或“Run”从 Eclipse 4.2 (20120614-1722) 运行它时(我没有为 Eclipse 或项目设置任何额外的编码首选项),我得到以下结果:

windows-1252

这对我来说似乎是正确的。

但是当我使用 ANT 1.8.2 将其打包到具有默认设置的 JAR 中时:

<project name="Test" default="dist" basedir=".">
    <description>
        Simple build XML
    </description>
    <!-- set global properties for this build -->
    <property name="src" location="src"/>
    <property name="build" location="build"/>
    <property name="dist"  location="dist"/>

    <target name="init">
        <!-- Create the build directory structure used by compile -->
        <delete dir="${build}"/>
        <mkdir dir="${build}"/>
    </target>

    <target name="compile" depends="init" description="compile the source" >
        <!-- Compile the java code from ${src} into ${build} -->
        <javac srcdir="${src}" destdir="${build}" includeantruntime="false"/>
    </target>

    <target name="dist" depends="compile" description="generate the distribution" >
        <!-- Create the distribution directory -->
        <delete dir="${dist}"/>
        <mkdir dir="${dist}"/>
        <!-- Put everything from ${build} into the test.jar file -->
        <jar jarfile="${dist}/test.jar" basedir="${build}">
            <manifest>
                <attribute name="Main-Class" value="org.Test"/>
            </manifest>
        </jar>
    </target>
</project>

运行时我得到以下结果:

>java -jar test.jar
windows-1251

我希望在这里得到相同的结果。我究竟做错了什么?那么确定默认字符集的正确方法是什么?

更新:问这个问题的原因是,我并没有真正读取或写入文件,我可以在其中手动指定编码。我只是从 javax.sound.sampled.Mixer.Info.getName()返回了一个字符串, 并且需要在不同的系统字符集中正确显示它。

Update2:看来,原因是 javax.sound.sampled.Mixer.Info.getName() 使用 CP1251 对“系统字符集”特定结果进行编码,所以我需要将其解码回“系统字符集”。但是如何发现呢?

4

1 回答 1

2

答案是你永远不应该依赖默认的字符编码:

如何在 Java 中查找默认字符集/编码?

设置默认的 Java 字符编码?

相反,当您写入或读取时,您需要明确指定所需的编码。

例如,应该首选第二个构造函数。

InputStreamReader(InputStream in) 
InputStreamReader(InputStream in, String charsetName) 
于 2013-01-25T16:22:37.600 回答