CSV文件读写

一、写入内容到 csv 文件,内容以英文逗号 “,” 分隔,且无中文乱码。若 csv 文件内容本身有逗号,则用双引号括起来。源码如下所示。

package *****.test;

import java.io.*;

/**
 * @description csv 文件写入,内容以英文逗号分隔,无中文乱码,且Excel打开无中文乱码
 * @date 2019/4/3 15:20
 */
public class TestMethod {
    public static void main(String[] args) {
    	String csvFilePath = "D://test";
        String fileName = "//test.csv";
        File folder = new File(csvFilePath);

        // 判断文件夹路径是否存在
        if (!folder.exists() && !folder.isDirectory()) {
            System.out.println("文件夹路径不存在,创建路径:" + csvFilePath);
            folder.mkdirs();
        }

        try {
            FileOutputStream fos = new FileOutputStream(csvFilePath + fileName);
            // 对文件添加 BOM 头
            fos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            BufferedWriter out = new BufferedWriter(osw);

            out.write("20190415" + ",");
            out.write("商户1" + ",");
            out.write("\"测试1,内容1\"");
            out.newLine();

            out.write("20190416" + ",");
            out.write("商户2" + ",");
            out.write("价钱2");
            out.newLine();

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

文件内容如下图所示:
csv 文件内容。无中文乱码。
二、读取逗号分隔的csv文件内容,解析得到每一列数据。源码如下所示。

package *****.test;

import java.io.*;

/**
 * @description 读取逗号分隔的 csv 文件,打印每行每列数据。双引号内的内容若含逗号,也不分割
 * @date 2019/4/8 15:20
 */
public class ReadCsv {

    public static void main(String[] args) {
        String location = "D://test//test.csv";

        String line;
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(location), "utf-8");
            BufferedReader reader = new BufferedReader(isr);
            while ((line = reader.readLine()) != null) {
                // 双引号内的逗号不分割,双引号外的逗号进行分割
                String[] lines = line.trim().split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)", -1);

                for (String str : lines) {
                    System.out.println(str + ";");
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println(location + "文件未找到");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/** 执行结果如下所示:
20190415;
商户1;
"测试1,内容1";
20190416;
商户2;
价钱2;
**/

发布了32 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/piaoranyuji/article/details/89335039