有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在不同IDE中的Junit测试结果不同

import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import java.io.FileReader;

public class Test1 {

    @org.junit.Test
    public void main() throws Exception {
        SAXBuilder sax = new SAXBuilder();
        Document doc = sax.build(new FileReader("resources/file.xml"));
        System.out.println(doc.getRootElement().getText());
    }
}

文件。xml包含以下内容:<root>©</root>编码是UTF-8

使用libsjdom2-2.06、hamcrest-core-1.3和junit-4.11

当我在IntelliJ中运行这个时,输出是这样的:©

当我在NetBeans中运行它时,输出是这样的:©

如果我将代码放到publicstaticvoidmain并运行它,那么一切都是正常的

如果我将FileReader更改为FileInputStream,则一切正常

如果我将FileReader更改为StringReader("<root>©</root>"),则一切正常

可能是什么


共 (1) 个答案

  1. # 1 楼答案

    读取文件时没有指定字符集,因此它使用JVM默认值,从IntelliJ运行的afaik通常默认为UTF-8,而Eclipse(至少在Windows上)默认为默认的非unicode字符集(例如西欧的Cp1252)

    您需要明确,如^{}文档中所述:

    The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

    换言之:

    new InputStreamReader(new FileInputStream("resources/file.xml"), StandardCharsets.UTF_8)
    

    或者,让SAXBuilder为您处理这个问题,然后给它一个InputStream。我相信——但我不是100%确定——这将决定XML声明的字符集:

    sax.build(new FileInputStream("resources/file.xml"))