4

我有一个 Java 项目,它读取 UTF-8 编码的 .txt 文件以构造显示的字符串。在 Eclipse 中运行,文件按预期读取和显示,但在我的 ant 构建之后,字符并没有按应有的方式出现。

这是我的 build.xml 文件

<?xml version="1.0"?>
<project name="Rutherford" default="jar">

    <property name="libsSrc" value="libs"/>
    <property name="build" value="build"/>
    <property name="classes" value="build/classes"/>
    <property name="jar" value="build/jar"/>
    <property name="libs" value="build/libs"/>

    <path id="classpath">
            <fileset dir="${libsSrc}" includes="*.jar"/>
    </path>

    <pathconvert property="mf.classpath" pathsep=" ">
            <path refid="classpath"/>
            <mapper>
                    <chainedmapper>
                            <flattenmapper/>
                            <globmapper from="*.jar" to="lib/*.jar"/>
                    </chainedmapper>
            </mapper>
    </pathconvert>

    <target name="clean" description="remove intermediate files">
        <delete dir="build"/>
    </target>

    <target name="compile" description="compile the Java source code to class files">
        <mkdir dir="${classes}"/>
        <javac srcdir="." destdir="${classes}" classpathref="classpath">
            <compilerarg line="-encoding utf-8"/>
        </javac>
    </target>

    <target name="jar" depends="compile" description="create a Jar file for the application">
        <mkdir dir="${jar}"/>
        <jar destfile="${jar}/App.jar">
            <zipgroupfileset dir="${libsSrc}" includes="*.jar"/>
            <fileset dir="${classes}" includes="**/*.class"/>
            <manifest>
                <attribute name="Main-Class" value="nat.rutherford.DesktopStarter"/>
                <attribute name="Class-Path" value="${mf.classpath}"/>
            </manifest>
        </jar>
    </target>

</project>

我尝试使用 UTF-8 字符编码进行编译

<compilerarg line="-encoding utf-8"/>

但显然这还不够,我需要修改什么才能让它工作?

谢谢

编辑 1

我读了 .txt 文件。

public String fileToString(String file) {
    InputStream in = new BufferedInputStream(Gdx.files.internal(file).read());
    return new Scanner(in).useDelimiter("\\A").next();
}

它将一个字符串返回给一个字符串变量,然后我只需将这个字符串传递给一个对象

在eclipse中编译和运行时它工作正常。

编辑 2

这是修复

public String fileToString(String file) {
    InputStream in = new BufferedInputStream(Gdx.files.internal(file).read());
    return new Scanner(in, "UTF-8").useDelimiter("\\A").next();
}

当你知道在哪里看时很简单!哈哈谢谢!

4

1 回答 1

3

根据文档,使用encoding='utf-8'而不是compiler-arg.

但是......我怀疑你的问题是运行时,而不是编译时间。OutputStreamWriter您是否在不传递编码的情况下创建对象?或者将有趣的字符传递给System.out.println? 或相应地InputStreamReaderScanner?在这种情况下,解决方法是添加-Dfile.encoding=utf-8到命令行。

于 2012-01-02T23:07:43.110 回答