1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package cn.com.ctop.common.utils;
- import com.csvreader.CsvReader;
- import com.csvreader.CsvWriter;
- import java.io.File;
- import java.io.IOException;
- import java.nio.charset.Charset;
- import java.util.ArrayList;
- import java.util.List;
- public class CsvUtils {
- public static void checkandCreateFile(String outPath) {
- File file = new File(outPath);
- try {
- if (!file.exists()) {
- file.createNewFile();
- System.out.println("文件不存在,新建成功!");
- } else {
- System.out.println("文件存在!");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static List<String[]> readCSV(String inPath, String charset) throws IOException {
- List<String[]> list = new ArrayList<>();
- CsvReader reader = new CsvReader(inPath, ',', Charset.forName(charset));
- reader.readHeaders();
- while (reader.readRecord()) {
- list.add(reader.getValues());
- }
- reader.close();
- for (int row = 0; row < list.size(); row++) {
- int length = list.get(row).length;
- if (length > 0) {
- for (int i = 0; i < length; i++) {
- System.out.print(list.get(row)[i] + ",");
- }
- }
- System.out.println("");
- }
- return list;
- }
- public static void writeCSV(String outPath, List<String[]> data) throws IOException {
- CsvUtils.checkandCreateFile(outPath);
- CsvWriter wr = new CsvWriter(outPath, ',', Charset.forName("gb2312"));
- String[] header = {"Name", "Province", "City", "Address", "Tel", "Website", "Server_content", "Jigou_cengji", "Type", "Parent_level1", "Parent_level2", "Branch_level"};
- wr.writeRecord(header);
- for (int i = 0; i < data.size(); i++) {
- String[] dataString = data.get(i);
- wr.writeRecord(dataString);
- }
- wr.close();
- }
- public static void main(String[] args) throws IOException {
- String[] header = new String[]{"日期", "plan", "广告组", "花费", "曝光数", "点击数", "行为数", "点击率", "行为率", "平均千次曝光花费", "平均点击单价", "平均行为单价", "提交按钮点击", "表单提交率", "表单提交单价"};
- String inPath = "D:\\工作文件\\360借条\\effect_unit_2019-08-02-00_2019-08-02-00.csv";
- String outPath = "D:\\工作文件\\360借条\\effect_unit_2019-08-02-00_2019-08-02-00_bak.csv";
- List<String[]> list = CsvUtils.readCSV(inPath, "utf8");
- CsvUtils.writeCSV(outPath, list);
- }
- }
|