• 用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>
    
    复制代码
  • 相关阅读:
    物理分辨率与逻辑分辨率,pt与px
    JBPM学习(四):执行流程实例
    JBPM学习(三):管理流程定义
    JBPM学习(二):ProcessEngine与Service API
    JBPM学习(一):实现一个简单的工作流例子全过程
    jbpm与spring hibernate struts整合
    代理模式 自己写的
    java反射与代理模式
    使用freemarker生成html
    freemarker 数字,字符的操作
  • 原文地址:https://www.cnblogs.com/jpfss/p/10072146.html
Copyright © 2020-2023  润新知