Java:Apache-Commons CSV文件的读和写

摘要:

CSV(Comma-Separated Values)逗号分隔值(有时也称为字符分隔值),因为分隔字符也可以不是逗号),文件是以纯文本形式存储表格数据,包括数字和文本。Apache Commons CSV下载地址: http://commons.apache.org/proper/commons-csv/download_csv.cgi

Java Bean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.what21.apache.commons.csv;
 
public class User {
 
     private String username;
     
     private String password;
     
     private String name;
     
     private int age;
 
     public User(String username,String password,String name, int age){
         this .username = username;
         this .password = password;
         this .name = name;
         this .age = age;
     }
     
     public String getUsername() {
         return username;
     }
 
     public void setUsername(String username) {
         this .username = username;
     }
 
     public String getPassword() {
         return password;
     }
 
     public void setPassword(String password) {
         this .password = password;
     }
 
     public String getName() {
         return name;
     }
 
     public void setName(String name) {
         this .name = name;
     }
 
     public int getAge() {
         return age;
     }
 
     public void setAge( int age) {
         this .age = age;
     }
     
     @Override
     public String toString() {
         StringBuilder sb = new StringBuilder();
         sb.append( "username : " ).append( this .getUsername());
         sb.append( ", password : " ).append( this .getPassword());
         sb.append( ", name : " ).append( this .getName());
         sb.append( ", age : " ).append( this .getAge());
         return sb.toString();
     }
 
}
输出CSV文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.what21.apache.commons.csv;
 
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
 
/**
  * @author ashraf
  *
  */
public class CsvFileWriter {
     
     //CSV文件分隔符
     private static final String NEW_LINE_SEPARATOR = "\n" ;
     
     //CSV文件头
     private static final Object [] FILE_HEADER = { "用户名" , "密码" , "名称" , "年龄" };
     
     /**
      * 写CSV文件
      *
      * @param fileName
      */
     public static void writeCsvFile(String fileName) {
         FileWriter fileWriter = null ;
         CSVPrinter csvFilePrinter = null ;
         //创建 CSVFormat
         CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
         try {
             //初始化FileWriter
             fileWriter = new FileWriter(fileName);
             //初始化 CSVPrinter
             csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
             //创建CSV文件头
             csvFilePrinter.printRecord(FILE_HEADER);
 
             // 用户对象放入List
             List userList = new ArrayList ();
             userList.add( new User( "zhangsan" , "123456" , "张三" , 25 ));
             userList.add( new User( "lisi" , "123" , "李四" , 23 ));
             userList.add( new User( "wangwu" , "456" , "王五" , 24 ));
             userList.add( new User( "zhaoliu" , "zhaoliu" , "赵六" , 20 ));
             
             // 遍历List写入CSV
             for (User user : userList) {
                 List userDataRecord = new ArrayList();
                 userDataRecord.add(user.getUsername());
                 userDataRecord.add(user.getPassword());
                 userDataRecord.add(user.getName());
                 userDataRecord.add(String.valueOf(user.getAge()));
                 csvFilePrinter.printRecord(userDataRecord);
             }
             System.out.println( "CSV文件创建成功~~~" );
             
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 fileWriter.flush();
                 fileWriter.close();
                 csvFilePrinter.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     
     /**
      * @param args
      */
     public static void main(String[] args){
         writeCsvFile( "c://users.csv" );
     }
     
}
读取CSV文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.what21.apache.commons.csv;
 
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
 
/**
  * @author ashraf_sarhan
  *
  */
public class CsvFileReader {
     
     //CSV文件头
     private static final String [] FILE_HEADER = { "用户名" , "密码" , "名称" , "年龄" };
     
     /**
      * @param fileName
      */
     public static void readCsvFile(String fileName) {
         FileReader fileReader = null ;
         CSVParser csvFileParser = null ;
         //创建CSVFormat(header mapping)
         CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
         try {
             //初始化FileReader object
             fileReader = new FileReader(fileName);
             //初始化 CSVParser object
             csvFileParser = new CSVParser(fileReader, csvFileFormat);
             //CSV文件records
             List csvRecords = csvFileParser.getRecords();
             // CSV
             List userList = new ArrayList();
             //
             for ( int i = 1 ; i < csvRecords.size(); i++) {
                 CSVRecord record = csvRecords.get(i);
                 //创建用户对象填入数据
                 User user = new User(record.get( "用户名" ), record.get( "密码" ),
                             record.get( "名称" ), Integer.parseInt(record.get( "年龄" )));
                 userList.add(user);
             }
             // 遍历打印
             for (User user : userList) {
                 System.out.println(user.toString());
             }
         }
         catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 fileReader.close();
                 csvFileParser.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     
     /**
      * @param args
      */
     public static void main(String[] args){
         readCsvFile( "c://users.csv" );
     }
 
}
 PS:与javacsv相比,读取速度慢,主要在于组装对象占用了大量的事件。

你可能感兴趣的:(Java)