Search code examples
javaarrayseclipsecsvopencsv

Appending data below the existing data in csv file Java


I have a csv file which contains 14 columns and 5 rows. I'm reading contents of last column and I'm performing some mathematical operation on the column values and saving that in an array named exposureFactor[]. Now I have to write that array column wise below the first column skiping a row which is getting done perfectly. But when I run the program again it gives me this error.

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at java.base/java.util.stream.ReferencePipeline$4$1.accept(ReferencePipeline.java:212)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.base/java.util.stream.IntPipeline.toArray(IntPipeline.java:538)
at com.sajood.Readingcsv.appendCol.main(appendCol.java:28)

Can someone please highlight the issue. It's a project given to me and it's deadline is in 2 days.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;

public class appendCol {

public static void main(String[] args) throws IOException {
    int sum = 0;
    String[] data5;
    CSVReader reader5 = new CSVReader(new FileReader("D:\\new.csv"));
    String[] nextLine5;
    List<String> li = new ArrayList<String>();
    while (null != (nextLine5 = reader5.readNext())) {
        li.add(nextLine5[nextLine5.length - 1]);

    }
    String[] tempe = li.toArray(new String[0]);
    String[] exp = Arrays.copyOfRange(tempe, 1, tempe.length);
    data5 = Arrays.toString(exp).replace("[", "").replace("]", "").replace("\"", "").replace(" ", "").split(",");
    int[] weightage = Arrays.stream(data5).mapToInt(Integer::parseInt).toArray(); 
    for (int i = 0; i < weightage.length; i++) {
        sum += weightage[i];
    }
    int average = sum / 6;
    String averageStr = String.valueOf(average);
    String exposureFactor[] = { "Exposure Factor", averageStr };
    FileWriter writer4 = new FileWriter("D:\\new.csv", true);
    CSVReader reader3 = new CSVReader(new FileReader("D:\\new.csv"), '\t', '\'', 6);
    if ((reader3.readNext()) != null) {
        return;
     } else {
        for (int j = 0; j < exposureFactor.length; j++) {
            if (j == 0) {
                writer4.append("\n");
            }
            writer4.append(String.valueOf(exposureFactor[j]));
            writer4.append("\n");
        }
        writer4.close();
    }
}

}


Solution

  • The only line it could be is:
    int[] weightage = Arrays.stream(data5).mapToInt(Integer::parseInt).toArray();

    I assume it's trying to parse your blank line as numbers. Why do you need to run it again after you've output your exposure factor?


    If your boss reeeeeeeally needs to run it twice in a row, the quick fix is to add a try catch and make it exit "gracefully."

    try {
        int[] weightage = Arrays.stream(data5).mapToInt(Integer::parseInt).toArray();
    } catch (NumberFormatException e) {
        System.out.println("Program has already been run.");
        System.exit(0);
    }
    

    You could also use that if ((reader3.readNext()) != null) check if you feel like reworking things.


    One more thing: you might want average to be a double instead of an int.