读写csv文件——考虑各种异常场景,源码

  CSV是以逗号间隔的文本文件,其文件以纯文本形式存储表格数据(数字和文本)。在JAVA中可以通过输出文件流的方式将数据写入CSV文件,通过BufferedReader类去读该路径中的文件,使用readLine方法进行逐行读取。

  •   写csv文件需要注意

  1、如果需要重复写文件,需要考虑删除已经存在的文件。

  •   读csv文件需要注意:

  1、文件路径是否存在

  2、文件表头是否正确,考虑兼容性问题时,只需要考虑是否存在需要的列即可

第一步:创建一个对象类

 1 package testCSV;
 2 
 3 public class Person {
 4     private String id;
 5     private String name;
 6     private String sex;
 7     private int age;
 8 
 9     public Person() {
10     }
11 
12     public Person(String id, String name, String sex, int age) {
13         this.id = id;
14         this.name = name;
15         this.sex = sex;
16         this.age = age;
17     }
18 
19     public String getId() {
20         return id;
21     }
22 
23     public void setId(String id) {
24         this.id = id;
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     public String getSex() {
36         return sex;
37     }
38 
39     public void setSex(String sex) {
40         this.sex = sex;
41     }
42 
43     public int getAge() {
44         return age;
45     }
46 
47     public void setAge(int age) {
48         this.age = age;
49     }
50 }

 

第二步:写和读csv文件

  1 package testCSV;
  2 
  3 import java.io.*;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import java.util.UUID;
  7 
  8 public class FileCsv {
  9     private static final String fileName = "D:\workspace\tmp\obj.csv";
 10     private static final String CSV_SPLIT = ",";
 11     private static int idIndex = -1;
 12     private static int nameIndex = -1;
 13     private static int sexIndex = -1;
 14     private static int ageIndex = -1;
 15 
 16     /**
 17      * 生成uuid
 18      *
 19      * @return 32位uuid
 20      */
 21     private static String getUUID32() {
 22         return UUID.randomUUID().toString().replace("-", "").toLowerCase();
 23     }
 24 
 25     /**
 26      * 构造数据
 27      *
 28      * @return 数据
 29      */
 30     private static List<Person> buildData() {
 31         List<Person> personList = new ArrayList<Person>(10);
 32         personList.add(new Person(getUUID32(), "张三", "female", 26));
 33         personList.add(new Person(getUUID32(), "李四", "man", 34));
 34         personList.add(new Person(getUUID32(), "王五", "female", 55));
 35         personList.add(new Person(getUUID32(), "一一", "female", 11));
 36         return personList;
 37     }
 38 
 39     /**
 40      * 写csv文件
 41      *
 42      * @return 文件名
 43      */
 44     public static String writeCsv() {
 45         File file = new File(fileName);
 46         if (null != file && file.exists()) {
 47             file.delete();
 48         }
 49         List<Person> personList = buildData();
 50         FileOutputStream out = null;
 51         OutputStreamWriter osw = null;
 52         BufferedWriter bw = null;
 53         try {
 54             out = new FileOutputStream(file);
 55             osw = new OutputStreamWriter(out, "UTF-8");
 56             bw = new BufferedWriter(osw);
 57             String title = "ID,NAME,SEX,AGE
";
 58             bw.append(title);
 59 
 60             for (Person data : personList) {
 61                 bw.append(data.getId());
 62                 bw.append(CSV_SPLIT);
 63                 bw.append(data.getName());
 64                 bw.append(CSV_SPLIT);
 65                 bw.append(data.getSex());
 66                 bw.append(CSV_SPLIT);
 67                 bw.append(String.valueOf(data.getAge()));
 68                 bw.append("
");
 69             }
 70         }
 71         catch (Exception e) {
 72             e.printStackTrace();
 73         }
 74         finally {
 75             if (bw != null) {
 76                 try {
 77                     bw.close();
 78                 }
 79                 catch (IOException e) {
 80                     e.printStackTrace();
 81                 }
 82             }
 83             if (osw != null) {
 84                 try {
 85                     osw.close();
 86                 }
 87                 catch (IOException e) {
 88                     e.printStackTrace();
 89                 }
 90             }
 91             if (out != null) {
 92                 try {
 93                     out.close();
 94                 }
 95                 catch (IOException e) {
 96                     e.printStackTrace();
 97                 }
 98             }
 99         }
100         return fileName;
101     }
102 
103     /**
104      * 表头正确性校验
105      *
106      * @param titleInfo 表头
107      * @return
108      */
109     private static Boolean checkTitle(String titleInfo) {
110         if (null == titleInfo || titleInfo.isEmpty()) {
111             return false;
112         }
113         String[] titles = titleInfo.split(CSV_SPLIT);
114         for (int i = 0; i < titles.length; i++) {
115             String titleName = titles[i];
116             if (titleName.equals("ID")) {
117                 idIndex = i;
118                 continue;
119             }
120             if (titleName.equals("NAME")) {
121                 nameIndex = i;
122                 continue;
123             }
124             if (titleName.equals("SEX")) {
125                 sexIndex = i;
126                 continue;
127             }
128             if (titleName.equals("AGE")) {
129                 ageIndex = i;
130                 continue;
131             }
132         }
133         if (idIndex == -1
134                 || nameIndex == -1
135                 || sexIndex == -1
136                 || ageIndex == -1) {
137             return false;
138         }
139         return true;
140     }
141 
142     /**
143      * 读取csv文件
144      *
145      * @return 数据
146      */
147     private static List<Person> readCsv() {
148         File file = new File(fileName);
149         if (null == file) {
150             return new ArrayList<Person>();
151         }
152         if (!file.exists()) {
153             return new ArrayList<Person>();
154         }
155         BufferedReader bufferedReader = null;
156         List<Person> personList = new ArrayList<Person>(10);
157         try {
158             bufferedReader = new BufferedReader(new FileReader(file));
159             if (!checkTitle(bufferedReader.readLine())) {
160                 return new ArrayList<Person>();
161             }
162             String line = "";
163             while (null != (line = bufferedReader.readLine())) {
164                 String[] personInfo = line.split(CSV_SPLIT);
165                 Person person = new Person();
166                 person.setId(personInfo[idIndex]);
167                 person.setName(personInfo[nameIndex]);
168                 person.setSex(personInfo[sexIndex]);
169                 person.setAge(Integer.parseInt(personInfo[ageIndex]));
170                 personList.add(person);
171             }
172         }
173         catch (IOException e) {
174             e.printStackTrace();
175         }
176         finally {
177             try {
178                 bufferedReader.close();
179             }
180             catch (IOException e) {
181                 e.printStackTrace();
182             }
183         }
184         return personList;
185     }
186 
187     public static void main(String[] args) {
188         writeCsv();
189         List<Person> personList = readCsv();
190         for (int i = 0; i < personList.size(); i++) {
191             Person person = personList.get(i);
192             System.out.println("id=" + person.getId()
193                     + ",name=" + person.getName()
194                     + ",sex=" + person.getSex()
195                     + ",age=" + String.valueOf(person.getAge()));
196         }
197     }
198 }

结果验证:
写文件


读文件

如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
 
 
原文地址:https://www.cnblogs.com/guobm/p/9737165.html