有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于读取UTF8 cvs和excel文件的java字节顺序标记

朋友

我必须使用BOM(字节顺序标记),以确保下载的文件在cvs和excel中以UTF-8格式正确显示

**

My question is can BOM be applied to FileOutputStream instead of OutputStream as below ?

***

    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();

共 (2) 个答案

  1. # 1 楼答案

    (如评论中所问。)

    在下面的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 + "\"?>");
        ...
    }
    

    使用文本可以更自然地使用编写器,因为不需要自己使用String.getBytes("UTF-8")转换字符串

  2. # 2 楼答案

    对。BOM位于任何数据流的开头,无论是通过网络还是文件。只需以相同的方式在开始时将BOM写入文件,只需写入FileOutputStream。无论如何,记住FileOutputStream是OutputStream的一种类型