朋友
我必须使用BOM ( Byte ),以确保下载的文件在cvs和excel的UTF-8格式是正确显示。
**
我的问题是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();
发布于 2013-12-10 12:11:30
(如评论中所问)
在下面的file
中,可能是文件、(文件)OutputStream或字符串(文件名)。
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")
来转换字符串。
发布于 2013-12-10 10:19:57
是。BOM位于任何数据流的开头,无论是在网络上还是在文件中。只需在开始时以相同的方式将BOM写入文件,只需将其写入FileOutputStream
。无论如何,记住FileOutputStream是OutputStream的一种类型。
https://stackoverflow.com/questions/20502176
复制