package com.wx.application.util;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CSVUtils {

    /**
     * @param file
     * @param sep  属性分隔符
     * @return
     * @throws FileNotFoundException
     */
    public static List<List<String>> parseCSV(File file, String sep) throws FileNotFoundException {
        List<List<String>> rows = new ArrayList<>();

        if (file == null) {
            return rows;
        }

        if (StringUtils.isEmpty(sep)) {
            sep = ",";
        }

        try {
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] values = line.split(sep);
                List<String> row = new ArrayList<>();

                for (String value : values) {
                    row.add(value);
                }

                rows.add(row);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return rows;
    }
}
