1 import java.io.BufferedReader;
2 import java.io.BufferedWriter;
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.OutputStreamWriter;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 import android.os.Environment;
12 /**
13 * CSV操作(导出和导入)
14 *
15 */
16 public class CSVUtil {
17 public static void testExportCsv(){
18 List<String> dataList=new ArrayList<String>();
19 dataList.add("1,黄忠,男");
20 dataList.add("2,汪倩,女");
21 dataList.add("3,黄球,女");
22 dataList.add("4,黄燕,女");
23 String path=Environment.getExternalStorageDirectory().getPath()+"/students.csv";
24 exportCsv(path, dataList);
25 }
26 /**
27 * 导出
28 *
29 * @param file csv文件(路径+文件名),csv文件不存在会自动创建
30 * @param dataList 数据
31 * @return
32 */
33 public static boolean exportCsv(String path, List<String> dataList){
34 File file =new File(path);
35 boolean isSucess=false;
36 FileOutputStream out=null;
37 OutputStreamWriter osw=null;
38 BufferedWriter bw=null;
39 try {
40 out = new FileOutputStream(file);
41 osw = new OutputStreamWriter(out);
42 bw =new BufferedWriter(osw);
43 if(dataList!=null && !dataList.isEmpty()){
44 for(String data : dataList){
45 bw.append(data).append("\r\n");
46 }
47 }
48 isSucess=true;
49 } catch (Exception e) {
50 isSucess=false;
51 }finally{
52 if(bw!=null){
53 try {
54 bw.close();
55 bw=null;
56 } catch (IOException e) {
57 e.printStackTrace();
58 }
59 }
60 if(osw!=null){
61 try {
62 osw.close();
63 osw=null;
64 } catch (IOException e) {
65 e.printStackTrace();
66 }
67 }
68 if(out!=null){
69 try {
70 out.close();
71 out=null;
72 } catch (IOException e) {
73 e.printStackTrace();
74 }
75 }
76 }
77 return isSucess;
78 }
79
80 /**
81 * 导入
82 *
83 * @param file csv文件(路径+文件)
84 * @return
85 */
86 public static List<String> importCsv(File file){
87 List<String> dataList=new ArrayList<String>();
88 BufferedReader br=null;
89 try {
90 br = new BufferedReader(new FileReader(file));
91 String line = "";
92 while ((line = br.readLine()) != null) {
93 dataList.add(line);
94 }
95 }catch (Exception e) {
96 }finally{
97 if(br!=null){
98 try {
99 br.close();
100 br=null;
101 } catch (IOException e) {
102 e.printStackTrace();
103 }
104 }
105 }
106
107 return dataList;
108 }
109 }