解决java下载csv中文乱码(加BOM头) 推荐第二种方法
发布日期:2021-05-04 20:53:48 浏览次数:17 分类:技术文章

本文共 1680 字,大约阅读时间需要 5 分钟。

使用csvWriter需要引入依赖:

net.sourceforge.javacsv
javacsv
2.0
File file = File.createTempFile("vehicle", ".csv");                        CsvWriter csvWriter = new CsvWriter(file.getAbsolutePath(), ',', Charset.forName("utf-8"));            //CsvWriter csv = new CsvWriter(file.getPath());            String[] headers = {"姓名","年龄","编号","性别","sex"};            csvWriter.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));            csvWriter.writeRecord(headers,false);            /*//csv.writeRecord(headers);            System.out.println(file.getParent());            System.out.println(file.getAbsolutePath());            System.out.println(file.getCanonicalPath());*/            System.out.println(file.getPath());            csvWriter.close();

解释:  代码中生成的utf-8文件没有加BOM(byte order marker 字节序列标示) 而微软的csv文件默认是有bom标示的,因此  Java代码生成的csv文件中的中文字被标示为??等.  所以解决的办法就是在文件的开头添加BOM标示就可以.

csvWriter.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));

或者加在要写出的内容前如:     String[] headers = {new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }),"姓名","年龄","编号","性别","sex"};

然而,第一种方法的缺点在于会在文件头部生成多余的空白字符,  所以推荐使用第二种方法:

第二种方法是用流的方式完美解决,如下

File file = File.createTempFile("vehicle", ".csv");            FileOutputStream fos = new FileOutputStream(file);            fos.write(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF});            CsvWriter csvWriter = new CsvWriter(fos, ',', Charset.forName("utf-8"));            String[] headers = {"姓名","年龄","编号","性别","sex"};            csvWriter.writeRecord(headers);            csvWriter.close();

先把标示符号用流的方式传过去  这样文件内就会把他识别为标示  而不是标示字符串, 后面就可以传递自己需要的内容啦

 

 

上一篇:Spring boot配置日志
下一篇:[Java]response.setHeader()下载中文文件名问题

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月11日 12时06分43秒