栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java处理Csv文件案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java处理Csv文件案例

需求:

源文件:

包含不同城市一年里每一天的最高温度和最低温度。(文件中存在异常数据如图2)

经过处理后,得到某个城市,每个月的最高/最低温度

结果如下:

代码

1、maven引入依赖

        
            net.sourceforge.javacsv
            javacsv
            2.0
        

2、代码

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.nio.charset.Charset;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        try {
            List csvList = new ArrayList<>();
            String src = "D:\1.csv";
            CsvReader reader = new CsvReader(src, ',', Charset.forName("UTF-8"));
            reader.readHeaders();
            while (reader.readRecord()) {
                csvList.add(reader.getValues());
            }
            reader.close();

            Map> cityAnd12TempList = new HashMap<>();
            List temp12List = new ArrayList<>();
            // 处理元素
            int curMonth = 0;
            String curCity = "";
            String preCity = "";
            int lowTemp = 999;
            for (int i = 0; i < csvList.size(); i++) {
                String city = csvList.get(i)[0];
                String date = csvList.get(i)[1];
                String temp = csvList.get(i)[3];
                int month = getMonthByDate(date);
                int tempInt = 0;
                if("".equals(curCity)){
                    curCity = city;
                }

                if (curMonth == 0) {
                    curMonth = month;
                }

                // 如果已经满12月
                if(temp12List.size() == 12){
                    System.out.println("放入城市:"+preCity+" list内容:"+temp12List);
                    cityAnd12TempList.put(preCity,temp12List);
                    temp12List = new ArrayList<>();
                }

                if (curMonth != month) {
                    // 月份变换
                    temp12List.add(lowTemp);
                    System.out.println(curCity+"的第"+curMonth+" 月最低温度是"+lowTemp+" 当前List大小:"+temp12List.size());
                    lowTemp = 999;
                    curMonth = month;
                }

                if (!curCity.equals(city)) {
                    preCity = curCity;
                    curCity = city;
                }

                // 温度
                try {
                    if (temp.startsWith("-")) {
                        String subTemp = temp.substring(1, temp.length() - 1);
                        tempInt = -(Integer.parseInt(subTemp));
                    } else {
                        String subTemp = temp.substring(0, temp.length() - 1);
                        tempInt = Integer.parseInt(subTemp);
                    }
                } catch (NumberFormatException e) {
                    tempInt = 999;
                }

                // 比较得到最低温度
                if (tempInt < lowTemp) {
                    lowTemp = tempInt;
                }

            }

            // 写出文件
            writeOut(cityAnd12TempList);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    private static void writeOut(Map> cityAnd12TempList) {


        String dstFile = "D:\2.csv";
        try{
            CsvWriter writer = new CsvWriter(dstFile, ',', Charset.forName("UTF-8"));
            String[] headers = {"城市","1月最低温度","2月最低温度","3月最低温度","4月最低温度","5月最低温度",
                    "6月最低温度","7月最低温度","8月最低温度","9月最低温度","10月最低温度","11月最低温度","12月最低温度"};
            writer.writeRecord(headers);

            Set set = cityAnd12TempList.keySet();
            for (String city : set) {
                List list = cityAnd12TempList.get(city);
                String[] content = new String[13];
                content[0] = city;
                int i=1;
                for (Integer integer : list) {
                    content[i++] = String.valueOf(integer);
                }
                writer.writeRecord(content);
            }

            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    
    private static int getMonthByDate(String date) {
        String substring = date.substring(5, 7);
        if (substring.startsWith("0")) {
            return Integer.parseInt(substring.substring(1));
        }
        return Integer.parseInt(substring);
    }
}

总结:

读文件:

List csvList = new ArrayList<>();
String src = "D:\1.csv";
CsvReader reader = new CsvReader(src, ',', Charset.forName("UTF-8"));
reader.readHeaders();
while (reader.readRecord()) {
    csvList.add(reader.getValues());
}
reader.close();

写文件:

        String dstFile = "D:\2.csv";
        try{
            CsvWriter writer = new CsvWriter(dstFile, ',', Charset.forName("UTF-8"));
            String[] headers = {"表头1","表头2","表头3"};
            writer.writeRecord(headers);
            String[] content = {"1","2","3"};
            writer.writeRecord(content);
            
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号