2 * Copyright (C) 2017 CMCC, Inc. and others. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.usecaseui.server.util;
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;
27 import java.util.List;
30 public class CSVUtils {
32 private final static String NEW_LINE_SEPARATOR="\n";
33 private static Logger logger = LoggerFactory.getLogger(CSVUtils.class);
39 * @param filePath 创建的csv文件路径
41 public static void writeCsv(String[] headers,List<String[]> data,String filePath) {
43 CSVFormat formator = CSVFormat.DEFAULT.withHeader(headers);
44 String dir = filePath.substring(0,filePath.lastIndexOf('/'));
45 File file = new File(dir);
48 try(Writer writer = new FileWriter(filePath);
49 CSVPrinter printer = new CSVPrinter(writer,formator)){
50 for(String[] str : data){
51 printer.printRecord(str);
55 logger.info("CSV File Generate Success,FilePath:"+filePath);
56 }catch (IOException e){
57 logger.error("CSV File Generate Failure:"+e.getMessage());
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{
68 CSVFormat formator = CSVFormat.DEFAULT.withHeader(headers);
69 FileReader fileReader=new FileReader(filePath);
71 CSVParser parser=new CSVParser(fileReader,formator);
72 List<CSVRecord> records=parser.getRecords();