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

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

问题描述

我收到一个错误 io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence

解决办法是用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);

我正在读取 url 并将其写入文件 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()(或者至少调用output.flush()code> 在您重新打开文件以供输入之前.这可能是您出现问题的主要原因.

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.

然后,您不应该为此使用 FileReaderFileWriter,因为它始终使用平台默认编码(通常不是 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天全站免登陆