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 /** 12 * CSV操作(导出和导入) 13 * 14 */ 15 public class CSVUtil { 16 17 /** 18 * 导出 19 * 20 * @param file 21 * csv文件(路径+文件名),csv文件不存在会自动创建 22 * @param dataList 23 * 数据 24 * @return 25 */ 26 public static String exportCsv(File file, List<String> dataList) { 27 28 boolean isSucess = false; 29 30 if (!file.getParentFile().exists()) { 31 file.getParentFile().mkdirs(); 32 } 33 if (!file.exists()) { 34 try { 35 file.createNewFile(); 36 } catch (IOException e) { 37 throw new RuntimeException(e); 38 } 39 } 40 41 FileOutputStream out = null; 42 OutputStreamWriter osw = null; 43 BufferedWriter bw = null; 44 try { 45 out = new FileOutputStream(file); 46 osw = new OutputStreamWriter(out, "UTF-8"); 47 bw = new BufferedWriter(osw); 48 if (dataList != null && !dataList.isEmpty()) { 49 for (String data : dataList) { 50 bw.append(data).append(" "); 51 } 52 } 53 isSucess = true; 54 } catch (Exception e) { 55 e.printStackTrace(); 56 isSucess = false; 57 } finally { 58 if (bw != null) { 59 try { 60 bw.close(); 61 bw = null; 62 } catch (IOException e) { 63 e.printStackTrace(); 64 } 65 } 66 if (osw != null) { 67 try { 68 osw.close(); 69 osw = null; 70 } catch (IOException e) { 71 e.printStackTrace(); 72 } 73 } 74 if (out != null) { 75 try { 76 out.close(); 77 out = null; 78 } catch (IOException e) { 79 e.printStackTrace(); 80 } 81 } 82 } 83 84 return file.getAbsolutePath(); 85 } 86 87 /** 88 * 导入 89 * 90 * @param file 91 * csv文件(路径+文件) 92 * @return 93 */ 94 public static List<String> importCsv(File file) { 95 List<String> dataList = new ArrayList<String>(); 96 97 BufferedReader br = null; 98 try { 99 br = new BufferedReader(new FileReader(file)); 100 String line = ""; 101 while ((line = br.readLine()) != null) { 102 dataList.add(line); 103 } 104 } catch (Exception e) { 105 } finally { 106 if (br != null) { 107 try { 108 br.close(); 109 br = null; 110 } catch (IOException e) { 111 e.printStackTrace(); 112 } 113 } 114 } 115 return dataList; 116 } 117 118 public static void main(String[] args) { 119 // File file = new File("D:/s.csv"); 120 // CSVUtil.importCsv(file); 121 122 File file = new File("D:/222.csv"); 123 List<String> dataList = new ArrayList<String>(); 124 dataList.add("1"); 125 dataList.add("2"); 126 dataList.add("3"); 127 dataList.add("4"); 128 dataList.add("5"); 129 130 CSVUtil.exportCsv(file, dataList); 131 132 } 133 134 }