如何阅读在utf-8中写这个? [英] How to read write this in utf-8?

查看:90
本文介绍了如何阅读在utf-8中写这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误 io.MalformedByteSequenceException:2字节UTF-8序列的无效字节2

解决方案是以UTF-8读写文件。

The solution is to read and write file in UTF-8.

我的代码是:

InputStream input = null;
OutputStream output = null;
OutputStreamWriter bufferedWriter = new OutputStreamWriter( output, "UTF8");
input = new URL(url).openStream();
output = new FileOutputStream("DirectionResponse.xml");
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
   output.write(buffer, 0, length);
}
BufferedReader br = new BufferedReader(new FileReader("DirectionResponse.xml" ));
FileWriter fstream = new FileWriter("ppre_DirectionResponse.xml");
BufferedWriter out = new BufferedWriter(fstream);

我正在读取一个网址并将其写入文件 DirectionResponse.xml 。然后读取 DirectionResponse.xml 并将其写为* ppre_DirecionResponse.xml *进行处理。

I'm reading a url and writing it to a file DirectionResponse.xml. Then reading DirectionResponse.xml and writing the same as *ppre_DirecionResponse.xml* for processing.

如何更改此项以便以UTF-8完成阅读和写作?

推荐答案

首先,你需要调用 output.close()(或者至少调用输出.flush()在重新打开输入文件之前。这可能是导致问题的主要原因。

First, you need to call output.close() (or at least call output.flush() before you reopen the file for input. That's probably the main cause of your problems.

然后,你不应该使用 FileReader FileWriter ,因为它始终使用平台默认编码(通常不是UTF-8)。来自 FileReader 的文档

Then, you shouldn't use FileReader or FileWriter for this because it always uses the platform-default encoding (which is often not UTF-8). From the docs for FileReader:


此类的构造函数假定默认字符编码和默认字节缓冲区大小是合适的。

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.

使用 FileWriter 时遇到同样的问题。替换为:

You have the same problem when using a FileWriter. Replace this:

BufferedReader br = new BufferedReader(new FileReader("DirectionResponse.xml" ));

,如下所示:

BufferedReader br = new BufferedReader(new InputStreamReader(
    new FileInputStream("DirectionResponse.xml"), "UTF-8"));

同样适用于 fstream

这篇关于如何阅读在utf-8中写这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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