字节顺序标记为读取UTF-8 cvs和excel文件
友
我必须使用BOM(字节顺序标记)来确保以UTF-8格式下载的cvs和excel文件能正确显示。
**
我的问题是可以将BOM应用于FileOutputStream而不是OutputStream如下所示?
**
String targetfileName = reportXMLFileName.substring(0, reportXMLFileName.lastIndexOf(".") + 1); targetfileName += "xlsx"; File tmpFile=new File((filePath !=null?filePath.trim():"")+"/"+templateFile); FileOutputStream out = new FileOutputStream((filePath !=null?filePath.trim():"")+"/"+targetfileName); /* Here is the example*/ out.write(new byte[] {(byte)0xEF, (byte)0xBB, (byte)0xBF }); substitute(tmpFile, tmp, sheetRef.substring(1), out); out.close();
(如评论中所述)
在以下file
可能是File,(File)OutputStream或String(filename)。
final String ENCODING = "UTF-8"; PrintWriter out = new PrintWriter(file, ENCODING)))); try { out.print("\ufffe"); // Write the BOM out.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>"); ... } finally { out.close(); }
或者从Java 7开始:
try (PrintWriter out = new PrintWriter(f, ENCODING))))) { out.print("\ufffe"); // Write the BOM out.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>"); ... }
使用文本,使得使用Writer更为自然,因为不需要用String.getBytes("UTF-8")
来转换string。
是。 BOM位于任何数据stream的开始处,无论是通过networking还是文件。 只需以相同的方式将BOM写入文件中,就可以将其写入FileOutputStream
。 无论如何,请记住FileOutputStream 是一种OutputStreamtypes。