当前位置: 移动技术网 > IT编程>开发语言>Java > 读写csv文件——考虑各种异常场景,源码

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

2018年10月03日  | 移动技术网IT编程  | 我要评论

  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\r";
 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("\r");
 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 }

结果验证:
写文件


读文件

 


如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网