从文件读取时,我读取的第一行有一个奇怪的字符(使用 BufferedReader)。如何删除这个角色?我知道我可以手动完成,但我想以正确的方式完成。
图片(NetBeans 输出)
使用 OP 提供的链接中的相关代码,这里是对按预期工作的问题的答案。
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}