user2925516
user2925516

Reputation: 65

parsing CSV file in Java with skipping the next row if is the first field is empty

I am using Java, and I have a CSV file that consists of 10 column and 5 rows. I would like to parse it into another CSV file with the this condition. if the first cell from any row is empty, skip that row, and jump to the next and so on. My code only reads all the rows and prints them, I want to have that condition and write into another CSV file.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CSV {
public static void main(String[] args) throws FileNotFoundException {
    String x;
    Scanner scanner = new Scanner(new File("Book1.csv"));
    scanner.useDelimiter(",");
    while(scanner.hasNext()){

            System.out.print(scanner.next());

    }
    scanner.close();
}

}

Example:

see the attached image please.
enter image description here

Upvotes: 0

Views: 1961

Answers (2)

Cmoraski
Cmoraski

Reputation: 78

Instead of delimiting the whole file, delimit line by line:

public static void main(String[] args) throws FileNotFoundException {
    String x;
    Scanner scanner = new Scanner(new File("Book1.csv"));
    while(scanner.hasNextLine()){                // If there is another line in the file
        x = scanner.nextLine();                  // Extract that line
        String[] values = x.split(",");          // Split that line at the commas
        if (!values[0].equals("")) {             // If the first value is not equal to empty
            System.out.print(x);                 // Print the line
        }
    }
    scanner.close();
}

Upvotes: 1

dunadar
dunadar

Reputation: 1785

You can take advantage of the fact that each record is a different line. So, instead of using Scanner class directly over the File, you can retrieve full lines with BufferedReader#readLine():

BufferedReader br = new BufferedReader(new FileReader("Book1.csv"));
String myLine = br.readLine();
while (myLine != null) {
    // do whatever you want with the line

    // read new line
    myLine = br.readLine();
}

So that myLine contains Strings like the following:

"John,M,Mi,1111,US,OR,..."
",David,criss,2222,US,MI,..."

Once you have a line, trim() it and check if the first character is your delimiter. In that case, the line should be ignored.

myLine = myLine.trim();
if (",".equals(myLine.at(0))) {
    // First field empty. Ignore
} else {
    // First field not empty. Write to new file
}

Upvotes: 1

Related Questions