OpenCSV - copying one csv file to another while adding a column

僤鯓⒐⒋嵵緔 提交于 2020-01-07 04:49:08

问题


I am trying to read from one CSV file using OpenCSV. I then want to copy all the data from the input csv and output it to another csv file while adding a new column with information.

public void run_streets_tsv( String tsvIn, String tsvOut) throws Exception
{

    CSVReader reader = null; 
    CSVWriter writer = null;

    try
    {

        reader = new CSVReader((new FileReader(tsvIn)));
        writer = new CSVWriter(new FileWriter(tsvOut), '\t');

        String element [] = null;
        List<String[]> a = new ArrayList<String[]>();

        while((element = reader.readNext()) != null){
            for(int i = 0; i<element.length; i++){
                a.add(i, element);
                //a.add("JSON");  need to add this json element at the end of each column 
            }
        }
        writer.writeAll(a);
    }
    catch(Exception e)
    {
        throw e;
        } 
    finally
    {
        reader.close();
        writer.close();
        }
    }

Another method I am trying is like this (changing the while loop, all other code remains the same):

        String element [] = null;
        while((element = reader.readNext()) != null){
            ArrayList list = new ArrayList(Arrays.asList(reader));
            list.add(element);
            list.add("JSON");
            writer.writeNext(element);
        }

This does correctly print all the lines, but it just copies. I want to add that extra "JSON" column with its data.


回答1:


The following "enlarges" the element-Array by one, enabling you to put something in the newly created last index. Then just save that array.

import java.util.Arrays;

    String element[] = null;
    while((element = reader.readNext()) != null){
        element = Arrays.copyOf(element, element.length + 1);
        element[element.length - 1] = "JSON";
        writer.writeNext(element);
    }



回答2:


OK, you are close although I see a few errors.

'reader.readNext()' return a line from the input as a String array, we basically need to add an element to this for the output.

while((element = reader.readNext()) != null) {
    String[] output = getExpandedArray(element);
    a.add(output);
}

You will need to implement getExpandedArray, I will start it off.

private String[] getExpandedArray(String[] input) {
    String[] output = null;
    //Populate/create output from input, but with the array 1 bigger. 
    output[output.length -1] = "JSON";
    return output;
}


来源:https://stackoverflow.com/questions/44636523/opencsv-copying-one-csv-file-to-another-while-adding-a-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!