简体   繁体   中英

How can you split a csv file into multiple files based on the value of a column java?

I need to find a way to split a csv file into multiple csv files based on the value of a particular column of my input csv file. I need the name of the newly generated csv files to be the value of that column as well.

For example:

input CSV file = 

Col1,Col2,Col3
1,2,Cat
1,3,Cat
2,4,Dog
2,5,Dog

I want to split by Col3 so I get the following table and file name:

---------------- File name = Cat.csv
Col1,Col2,Col3
1,2,Cat
1,3,Cat



---------------- File name = Dog.csv
Col1,Col2,Col3
2,4,Dog
2,5,Dog

Any way to do this?

Thanks for any help.

So, far i can only do only reading file and saving in a object.

    package com.jcg;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CsvFileReader {

    private static final String COMMA_DELIMITER = ",";

    private static final int ORDER_ID_IDX = 0;
    private static final int ORDER_DATE_IDX = 1;
    private static final int ORDER_COUNTRY_IDX = 2;
    private static final int ORDER_VALUE = 3;

    public static void readCsvFile(String fileName) {

        BufferedReader fileReader = null;

        try {

            List<Order> orders = new ArrayList<Order>();

            String line = "";

            fileReader = new BufferedReader(new FileReader(fileName));

            fileReader.readLine();

            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    Order order = new Order(Long.parseLong(tokens[ORDER_ID_IDX]), tokens[ORDER_DATE_IDX],
                            tokens[ORDER_COUNTRY_IDX], tokens[ORDER_VALUE]);
                    orders.add(order);
                }
            }

            for (Order order : orders) {
                System.out.println(order.toString());

            }
        } catch (Exception e) {
            System.out.println("Error in CsvFileReader !!!");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error while closing fileReader !!!");
                e.printStackTrace();
            }
        }

    }

}

Order.java

    package com.jcg;

public class Order {

    private long id;
    private String dates;
    private String country;
    private String values;

    public Order(long id, String dates, String country, String values) {
        super();
        this.id = id;
        this.dates = dates;
        this.country = country;
        this.values = values;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getDates() {
        return dates;
    }

    public void setDates(String dates) {
        this.dates = dates;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getValues() {
        return values;
    }

    public void setValues(String values) {
        this.values = values;
    }

    @Override
    public String toString() {
        return "Order [id=" + id + ", dates=" + dates + ", country=" + country + ", values=" + values + "]";
    }
}

Since you have list of Order

List<Order> orders = new ArrayList<Order>();

Do group by on list List<Order> orders with key as Col3 (which is private String values ) and values as List<Order>

Map<String,List<Order>> result = orders.stream()
                           .collect(Collectors.groupingBy(Order::getValues));

Now for each entry in Map create .csv file with key and write write corresponding values to that file

result.forEach((key,value)->{
File newFile = new File(key+".csv");
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
 values.forEach(order->{
         StringBuilder builder = new StringBuilder();
         builder.append(order.getId()+",");
         builder.append(order.getDates()+",");
         builder.append(order.getCountry()+",");
         builder.append(order.getValues()+",");
         writer.write(builder.toString());
         writer.newLine();
        };
         writer.flush();
         writer.close();
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM