如何阅读以 utf-8 写这个? [英] How to read write this in 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.
然后,您不应该为此使用 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屋!