安全编码构造函数
让 Java 正确地通知您编码错误是很棘手的。对于InputStreamReader 和OutputStreamWriter 中的每一个,您必须使用四个备用构造函数中最冗长的 以及最少使用收到有关编码故障的适当异常。
对于文件 I/O,始终确保始终将花哨的编码器参数用作 OutputStreamWriter 和 InputStreamReader 的第二个参数:
Charset.forName("UTF-8").newEncoder()
还有其他更奇特的可能性,但三种更简单的可能性都不适用于异常处理。这些可以:
OutputStreamWriter char_output = new OutputStreamWriter(
new FileOutputStream("some_output.utf8"),
Charset.forName("UTF-8").newEncoder()
);
InputStreamReader char_input = new InputStreamReader(
new FileInputStream("some_input.utf8"),
Charset.forName("UTF-8").newDecoder()
);
至于运行
$ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere
问题在于,它不会对字符流使用完整的编码器参数形式,因此您将再次错过编码问题。
更长的例子
这是一个更长的例子,这个例子管理一个进程而不是一个文件,我们将两个不同的输入字节流和一个输出字节流全部提升为 UTF-8 字符流具有完整的异常处理:
// this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
Process
slave_process = Runtime.getRuntime().exec("perl -CS script args");
// fetch his stdin byte stream...
OutputStream
__bytes_into_his_stdin = slave_process.getOutputStream();
// and make a character stream with exceptions on encoding errors
OutputStreamWriter
chars_into_his_stdin = new OutputStreamWriter(
__bytes_into_his_stdin,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newEncoder()
);
// fetch his stdout byte stream...
InputStream
__bytes_from_his_stdout = slave_process.getInputStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stdout = new InputStreamReader(
__bytes_from_his_stdout,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
// fetch his stderr byte stream...
InputStream
__bytes_from_his_stderr = slave_process.getErrorStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stderr = new InputStreamReader(
__bytes_from_his_stderr,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
现在您有了三个在编码错误时都会引发异常的字符流,分别称为chars_into_his_stdin、chars_from_his_stdout 和chars_from_his_stderr。
这仅比您解决问题所需的复杂一些,我在此答案的前半部分给出了解决方案。关键是这是检测编码错误的唯一方法。
请不要让我开始谈论 PrintStreams 饮食异常。