How to count the number of cells that a java program can not read

CodIn :

I am trying to read a csv file and to count the cells that can not be read due to some error. Here is the code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import javax.swing.JFileChooser;

public class CSVReader {
    public static void main(String[] args) {
        JFileChooser dialogue = new JFileChooser();
        dialogue.showOpenDialog(null);
        String csvFile = dialogue.getSelectedFile().getAbsolutePath();
        System.out.println(csvFile);
        String line = "";
        String cvsSplitBy = ";";
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            while ((line = br.readLine()) != null) {
                    String[] country = line.split(cvsSplitBy);
                    System.out.println("cell1 = " + country[0] + " , next= " + country[1] + " ,  next= "+ country[2] + " , next= " + country[3] + " , next= "+ " ");

        }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

How can i do to count the cells not read?

Janac Meena :

Ideally, you want to have a "verifier method" that checks if your input is valid, and then increments a counter. But, using the code you already have posted, you can just add a counter in your catch block like so:

public class CSVReader {
    public static void main(String[] args) {
        int count = 0;// INITIALIZE COUNTER
        JFileChooser dialogue = new JFileChooser();
        dialogue.showOpenDialog(null);
        String csvFile = dialogue.getSelectedFile().getAbsolutePath();
        System.out.println(csvFile);
        String line = "";
        String cvsSplitBy = ";";
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            while ((line = br.readLine()) != null) {
                    String[] country = line.split(cvsSplitBy);
                    System.out.println("cell1 = " + country[0] + " , next= " + country[1] + " ,  next= "+ country[2] + " , next= " + country[3] + " , next= "+ " ");

        }

        } catch (IOException e) {
            count++; // INCREMENT COUNTER
            e.printStackTrace();
        }

    }

}

Note, you would likely need to wrap the whole thing in a loop so that it continues even after throwing the exception.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334317&siteId=1