原因是Excel通过文件的BOM头来判断文件编码 https://blog.csdn.net/chichanma2003/article/details/100851467。
但是我的和他的不一样。
最后参考了 https://stackoverflow.com/questions/4389005/how-to-add-a-utf-8-bom-in-java 成功了!
但是,为什么 \ufeff = 0xEF 0xBB 0xBF 呢?长得不像啊!
void writeFile(String filename, String s) {
File file = new File(MainActivity.dir, filename);
try {
BufferedWriter BW = new BufferedWriter(new FileWriter(file, false)); //false覆盖
if(filename.endsWith(".csv")){
BW.write('\ufeff'); // Excel通过文件的BOM头来判断文件编码
BW.flush();
}
BW.write(s);
BW.flush();
Toast.makeText(getApplicationContext(), "写文件 " + MainActivity.dir + File.separator + filename + " 成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}