使用Java读写CSV文件

时间:2016-06-21 10:27:15

标签: java string csv bufferedreader filewriter

我有一个CSV日志文件,它包含很多行,如下所示:

2016-06-21 12:00:00,000 : helloworld: header1=2;header2=6;header=0

我想将它们写入新的CSV文件。

public void readLogFile() throws Exception
{
    String currentLine = "";
    String nextLine = "";

    BufferedReader reader = new BufferedReader(new FileReader(file(false)));
    while ((currentLine = reader.readLine()) != null)
    {
        if (currentLine.contains("2016") == true)
        {
            nextLine = reader.readLine();
            if (nextLine.contains("helloworld") == true)
            {                   
                currentLine = currentLine.substring(0, 23);
                nextLine = nextLine.substring(22, nextLine.length());

                String nextBlock = replaceAll(nextLine);
                System.out.println(currentLine + " : helloworld: " + nextBlock);

                String[] data = nextBlock.split(";");
                for (int i = 0, max = data.length; i < max; i++)
                {
                    String[] d = data[i].split("=");
                    map.put(d[0], d[1]);
                }
            }
        }
    }
    reader.close();
}

这是我编写内容的方法:

public void writeContentToCsv() throws Exception
{
    FileWriter writer = new FileWriter(".../file_new.csv");
    for (Map.Entry<String, String> entry : map.entrySet())
    {
        writer.append(entry.getKey()).append(";").append(entry.getValue()).append(System.getProperty("line.separator"));
    }
    writer.close();
}

这是我想要的输出:

header1; header2; header3
2;6;0
1;5;1
5;8;8
...

目前,CSV文件如下所示(仅显示一个数据集):

header1;4
header2;0
header3;0

任何人都可以帮我修复代码吗?

3 个答案:

答案 0 :(得分:1)

创建一个类来存储标头值,并将其存储在列表中。 迭代列表以保存结果。

当前使用的地图只能存储2个值(它存储标题值(名称对应的值)

map.put(d [0],d [1]); 这里d [0]将是header1而d [1]将是4(但我们只想从这里开始4)

    class Headervalues {
    String[] header = new String[3];
}

public void readLogFile() throws Exception
{
    List<HeaderValues> list = new ArrayList<>();
    String currentLine = "";
    BufferedReader reader = new BufferedReader(new FileReader(file(false)));
    while ((currentLine = reader.readLine()) != null)
    {
        if (currentLine.contains("2016") && currentLine.contains("helloworld"))
        {

                String nextBlock = replaceAll(currentLine.substring(22, currentLine.length());

                String[] data = nextBlock.split(";");
                HeaderValues headerValues = new HeaderValues();
                //Assuming data.length will always be 3.
                for (int i = 0, max = data.length; i < max; i++)
                {
                    String[] d = data[i].split("=");
                    //Assuming split will always have size 2
                   headerValues.header[i] = d[1];
                }
                list.add(headerValues)
            }
        }
    }
    reader.close();
}
public void writeContentToCsv() throws Exception
{
    FileWriter writer = new FileWriter(".../file_new.csv");
    for (HeaderValues value : headerValues)
    {
        writer.append(value.header[0]).append(";").append(value.header[1]).append(";").append(value.header[2]);
    }
    writer.close();
}

答案 1 :(得分:1)

用于写入CSV

public void writeCSV() {

        // Delimiter used in CSV file
        private static final String NEW_LINE_SEPARATOR = "\n";

        // CSV file header
        private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };

        String fileName = "fileName.csv");
        List<Objects> objects = new ArrayList<Objects>();
        FileWriter fileWriter = null;
        CSVPrinter csvFilePrinter = null;

        // Create the CSVFormat object with "\n" as a record delimiter
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);

        try {
            fileWriter = new FileWriter(fileName);

            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

            csvFilePrinter.printRecord(FILE_HEADER);

            // Write a new student object list to the CSV file
            for (Object object : objects) {
                List<String> record = new ArrayList<String>();

                record.add(object.getValue1().toString());
                record.add(object.getValue2().toString());
                record.add(object.getValue3().toString());

                csvFilePrinter.printRecord(record);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

答案 2 :(得分:0)

使用org.apache.commons.csv.CSVParser读写CSV文件。

public void appendCSV(){
        String [] records = {};
        String csvWrite= "";
        Boolean status = false;

        try(BufferedReader csvReaders = new BufferedReader(new FileReader("csvfile.csv"));
                CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(csvReaders);
                ) {

            for(CSVRecord record : parser) {
                status= record.get("Microservice").equalsIgnoreCase(apipath);
                int status_code=0;
                String httpMethod = record.get("Method");

                if(status==true) {
                csvWrite = record.get("apiName")+"-"+record.get("Microservice")+"-"+record.get("R_Data")+"-"+record.get("Method")+"-"+record.get("A_Status")+"-"+400+"-"+record.get("A_Response")+"-"+"{}";
                    records = csvWrite.split("-");
                    CSVWriter writer = new CSVWriter(new FileWriter(pathTowritecsv,true));
                    writer.writeNext(records);
                    writer.close();

                }else {

                }
            }
        } 

        catch (Exception e) {
            System.out.println(e);
        }

}