Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

Java: Using InputStream and Apache Commons CSV without line numbers

This is probably very simple, but I have not been able to find an option to do this. I'm trying to Apache Commons CSV to read a file for later validations. The CSV in question is submitted as an Input Stream, which seems to add an additional column to the file when it reads it, containing the line numbers. I would like to be able to ignore it, if possible, as the header row does not contain a number, which causes an error. Is there an option already in InputStream to do this, or will I have to set up some kind of post processing?

The code I'm using is as follows:

public String validateFile(InputStream filePath) throws Exception{
        System.out.println("Sending file to reader");
        System.out.println(filePath);
        InputStreamReader in = new InputStreamReader(filePath);
        //CSVFormat parse needs a reader object
        System.out.println("sending reader to CSV parse");
        for (CSVRecord record : CSVFormat.DEFAULT.withHeader().parse(in)) {
            for (String field : record) {
                System.out.print(""" + field + "", ");
            }
            System.out.println();
        }
        return null;
    }

When using withHeader(), I end up with the following error:

java.lang.IllegalArgumentException: A header name is missing in [, Employee_ID, Department, Email]

and I can't simply skip it, as I will need to do some validations on the header row.

Also, here is an example CSV file:

"Employee_ID", "Department", "Email"
"0123456","Department of Hello World","[email protected]"

EDIT: Also, The end goal is to validate the following:

  1. That there are columns called "Employee_ID", "Department", and "Email". For this, I think I'll need to remove .withHeader().
  2. Each line is comma delimited.
  3. There are no empty cells values
question from:https://stackoverflow.com/questions/65602836/java-using-inputstream-and-apache-commons-csv-without-line-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...