zoukankan      html  css  js  c++  java
  • 用Java对CSV文件进行读写操作

    需要jar包:javacsv-2.0.jar

    读操作

    复制代码
    // 读取csv文件的内容
        public static ArrayList<String> readCsv(String filepath) {
            File csv = new File(filepath); // CSV文件路径
            csv.setReadable(true);//设置可读
            csv.setWritable(true);//设置可写
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(csv));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String line = "";
            String everyLine = "";
            ArrayList<String> allString = new ArrayList<>();
            try {
                while ((line = br.readLine()) != null) // 读取到的内容给line变量
                {
                    everyLine = line;
                    System.out.println(everyLine);
                    allString.add(everyLine);
                }
                System.out.println("csv表格中所有行数:" + allString.size());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return allString;
    
    }</span></pre>
    
    复制代码

    写操作

    复制代码
    public void writeCSV(String path) {
            String csvFilePath = path;
    try {
            </span><span style="color: #008000">//</span><span style="color: #008000"> 创建CSV写对象 例如:CsvWriter(文件路径,分隔符,编码格式);</span>
            CsvWriter csvWriter = <span style="color: #0000ff">new</span> CsvWriter(csvFilePath, ',', Charset.forName("GBK"<span style="color: #000000">));
            </span><span style="color: #008000">//</span><span style="color: #008000"> 写内容</span>
            String[] headers = {"FileName","FileSize","FileMD5"<span style="color: #000000">};
            csvWriter.writeRecord(headers);
            </span><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i=0;i&lt;writearraylist.size();i++<span style="color: #000000">){
                String[] writeLine</span>=writearraylist.get(i).split(","<span style="color: #000000">);
                System.out.println(writeLine);
                csvWriter.writeRecord(writeLine);
            }
                       
            csvWriter.close();
            System.out.println(</span>"--------CSV文件已经写入--------"<span style="color: #000000">);
        } </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (IOException e) {
            e.printStackTrace();
        }
    }</span></pre>
    
    复制代码
  • 相关阅读:
    字节对齐的问题
    Combination Sum 和Combination Sum II
    Combinations
    算法导论 第六章 思考题6-3 Young氏矩阵
    算法导论 第六章 思考题 6-3 d叉堆
    算法导论 第六章 思考题 6-1 用插入的方法建堆
    Binary Tree Maximum Path Sum
    leetcode candy
    《程序设计与算法(二)算法基础》《第五周 分治》快速排序
    【Tesla】特斯拉Autopilot核心传感器解读之毫米波雷达篇
  • 原文地址:https://www.cnblogs.com/jpfss/p/10072146.html
Copyright © 2011-2022 走看看