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
347 views
in Technique[技术] by (71.8m points)

How to parse a csv file and store datails in java bean class

I need to parse a csv file and store the data into a java bean class. Like:

email,fname,lname
[email protected],abc,xyz

These details into a bean class. I am able to parse a csv file. How to store details in bean class.

private static List<List<String>> readTXTFile(String csvFileName) throws IOException {

     String line = null;
    BufferedReader stream = null;
    List<List<String>> csvData = new ArrayList<List<String>>();

    try {
        stream = new BufferedReader(new FileReader(csvFileName));
        while ((line = stream.readLine()) != null) {
            String[] splitted = line.split(",");
            List<String> dataLine = new ArrayList<String>(splitted.length);
            for (String data : splitted)
                dataLine.add(data);
            csvData.add(dataLine);
        }
    } finally {
        if (stream != null)
            stream.close();
    }

    return csvData;

}

the above code is parsing csv file but i want that data to be inserted in java bean class.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Create a POJO

private class Data{//You can make it public too, in a separate class
    String email;
    String fname;
    String lname;

    //Getters

    //Setters
}

In your original class you can use like this

List<Data> datas = new ArrayList<Data>();
try {
    stream = new BufferedReader(new FileReader(csvFileName));
    while ((line = stream.readLine()) != null) {
        String[] splitted = line.split(",");
        Data data = new Data();
        data.setEmail(splitted[0]);
        data.setFname(splitted[1]);
        data.setLname(splitted[2]);

        datas.add(data);
    }
} 

You will have all rows in your arraylist. You can put a null check to make it more efficient.


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

...