0

我想使用 openConnection 下载并保存 xml 文件。

问题是,当我保存文件时,字符集错误。

我的代码是:

URL url = new URL(partnersEntity.getUrl());

            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Content-Length", "500000");
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
            urlConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");


            Calendar calendar = Calendar.getInstance();
            Date now = calendar.getTime();
            Timestamp currentTimestamp = new Timestamp(now.getTime());

            File file = new File(myFile);

            FileWriter writer = new FileWriter(file);

            IOUtils.copy(urlConnection.getInputStream(), writer);
            writer.close();

之后在我的文件中我看到像“??”这样的标记 在特殊包机的地方。

我应该改变什么?

4

2 回答 2

2

在这种情况下不要使用 Reader/Writer,让 xml 保持原样。

        FileOutputStream out = new FileOutputStream(file);

        IOUtils.copy(urlConnection.getInputStream(), out);

通过使用 FileWriter,您正在使用平台默认字符集编写 xml 数据,这绝不是您想要做的。始终将 xml 视为二进制数据,而不是文本数据

于 2013-03-01T15:11:26.133 回答
1

(1) 检查您正在阅读的资源是否真的是 UTF-8。您要求使用“接受字符集”,但这并不能保证。然而。假设它是 UTF-8。

(2) 指定您正在使用的编写器的字符集。通过使用 FileWriter,您可以获得正在运行的环境的“默认”字符集......可能不是 UTF-8。最好使用 OutputStreamWriter 来具体说明。

OutputStream os = new OutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");

(3) 告诉副本如何解释传入的流:

IOUtils.copy(urlConnection.getInputStream(), writer, "UTF-8");
于 2013-03-01T15:10:11.193 回答