Search code examples
javastringcsvbufferedreaderfilewriter

Read and Write CSV File using Java


I have a CSV log file and it contains many rows like this:

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

I want to write them to a new CSV file.

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();
}

This is my method to write the content:

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();
}

This is the output I want to have:

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

Currently, the CSV file looks like this (only showing one dataset):

header1;4
header2;0
header3;0

Can anyone help me fix the code?


Solution

  • Create a class to store the header values, and store it in the list. Iterate over the list to save the results.

    The currently used map can only store 2 values (which it is storing the header value (name its corresponding value)

    map.put(d[0], d[1]); here d[0] will be header1 and d[1] will be 4 (but we want only 4 from here)

        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();
    }