change project structure
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / util / CSVUtils.java
1 /*
2  * Copyright (C) 2017 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.usecaseui.server.util;
17
18 import org.apache.commons.csv.CSVFormat;
19 import org.apache.commons.csv.CSVParser;
20 import org.apache.commons.csv.CSVPrinter;
21 import org.apache.commons.csv.CSVRecord;
22 import org.aspectj.util.FileUtil;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import java.io.*;
27 import java.util.List;
28
29
30 public class CSVUtils {
31     //CSV文件分隔符
32     private final static String NEW_LINE_SEPARATOR="\n";
33     private static Logger logger = LoggerFactory.getLogger(CSVUtils.class);
34
35
36     /**写入csv文件
37      * @param headers 列头
38      * @param data 数据内容
39      * @param filePath 创建的csv文件路径
40      * **/
41     public static void writeCsv(String[] headers,List<String[]> data,String filePath) {
42         try{
43             CSVFormat formator = CSVFormat.DEFAULT.withHeader(headers);
44             String dir = filePath.substring(0,filePath.lastIndexOf('/'));
45             File file = new File(dir);
46             if (!file.exists())
47                  file.mkdirs();
48             try(Writer writer = new FileWriter(filePath);
49                 CSVPrinter printer = new CSVPrinter(writer,formator)){
50                 for(String[] str : data){
51                     printer.printRecord(str);
52                 }
53             }
54
55             logger.info("CSV File Generate Success,FilePath:"+filePath);
56         }catch (IOException e){
57             logger.error("CSV File Generate Failure:"+e.getMessage());
58         }
59     }
60
61     /**读取csv文件
62      * @param filePath 文件路径
63      * @param headers csv列头
64      * @return CSVRecord 列表
65      * @throws IOException **/
66     public static List<CSVRecord> readCSV(String filePath, String[] headers) throws IOException{
67         //创建CSVFormat
68         CSVFormat formator = CSVFormat.DEFAULT.withHeader(headers);
69         FileReader fileReader=new FileReader(filePath);
70         //创建CSVParser对象
71         CSVParser parser=new CSVParser(fileReader,formator);
72         List<CSVRecord> records=parser.getRecords();
73         parser.close();
74         fileReader.close();
75         return records;
76     }
77
78 }