但是,我有以下代码,我希望它写为 UTF-8 文件来处理外来字符。有没有办法做到这一点,是否需要有一个参数?
非常感谢您对此提供的帮助。谢谢。
try {
BufferedReader reader = new BufferedReader(new FileReader("C:/Users/Jess/My Documents/actresses.list"));
writer = new BufferedWriter(new FileWriter("C:/Users/Jess/My Documents/actressesFormatted.csv"));
while( (line = reader.readLine()) != null) {
//If the line starts with a tab then we just want to add a movie
//using the current actor's name.
if(line.length() == 0)
continue;
else if(line.charAt(0) == '\t') {
readMovieLine2(0, line, surname.toString(), forename.toString());
} //Else we've reached a new actor
else {
readActorName(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
安全编码构造函数
让 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
。
这仅比您解决问题所需的复杂一些,我在此答案的前半部分给出了解决方案。关键是这是检测编码错误的唯一方法。
别让我开始谈论 PrintStream
的饮食异常。
关于java - 使用 FileWriter (Java) 以 UTF-8 格式写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852978/