14

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

解决方案是以 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* 相同的内容进行处理。

如何更改它以便以 UTF-8 进行读写?

4

2 回答 2

35

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

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

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

使用FileWriter. 替换这个:

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

像这样:

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

同样对于fstream.

于 2012-11-12T20:09:32.100 回答
2

用 Java 读写 UTF-8 文件

我看到你正在用 utf-8 写作,但没有专门用 utf-8 阅读。按照我在链接中提供的示例进行操作。

try {
   Reader reader =
      new InputStreamReader(
         new FileInputStream(args[0]),"UTF-8");
   BufferedReader fin = new BufferedReader(reader);
   Writer writer =
      new OutputStreamWriter(
         new FileOutputStream(args[1]), "UTF-8");
   BufferedWriter fout = new BufferedWriter(writer);
   String s;
   while ((s=fin.readLine())!=null) {
      fout.write(s);
      fout.newLine();
   }

            //Remember to call close. 
            //calling close on a BufferedReader/BufferedWriter 
            // will automatically call close on its underlying stream 
   fin.close();
   fout.close();
} catch (IOException e) {
   e.printStackTrace();
}
于 2012-11-12T20:06:31.107 回答