简体   繁体   中英

CSVWriter only writes last line in Java

I'm trying to get the print output and store it into an array of Strings in order to write the values in a CSV File. The problem that comes up is that when a run the code, from 100 lines printed, only the last line gets stored:

public void organize(String line) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter("out.csv"), '\t');

    String[] token = line.split(",");
    String[] DependencyItems = token[1].split(" ");
    List<String> entriesList;
    String[] entries;
    String row = "";

    for (int i = 0; i < DependencyItems.length; i++) {
            row = token[0] + "," + DependencyItems[i] + "," + token[2] + "," + token[3] + "," + token[5]+ "," + token[6]
            + "," + token[7]+ "," + token[8]+ "," + token[9] + "," + token[10] + "," + token[11] + "," + token[12]
            + "," + token[13] + "," + token[14] + "," + token[15] + "," + token[16]+ "," + token[17]
            + "," + token[18]+ "," + token[19]+ "," + token[20]+ "," + token[21] + "," + token[22]
            + "," + token[23]+ "," + token[24]+ "," + token[25]+ "," + token[26]+ "," + token[27]
            + "," + token[28]+ "," + token[29];
    }
    System.out.println(row);
    entriesList = Arrays.asList(row);
    entries = entriesList.toArray(new String[0]);
    writer.writeNext(entries);
    writer.close();
}

What I am doing wrong?

row = <big long string>

You are always resetting row then all of the stuff after the loop is just using the last value of row. If you want to use all the values, perhaps the code after the loop should be in the loop? At the very least it looks like these 2 lines belong in the loop.

System.out.println(row);
entriesList = Arrays.asList(row);

Note that if the scope of row was limited to just be inside the loop, then this may help to identify this type of issue as it would not be valid outside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM