Java csv文件读写

  1 package waf.fileformats.csv;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import java.util.regex.Matcher;
  6 import java.util.regex.Pattern;
  7 
  8 
  9 public class CSVFile 
 10 {
 11     private List<String> errors=new ArrayList<String>();
 12     private List<List<String>> datas=new ArrayList<List<String>>();
 13     private waf.file.File cvsFile=null;
 14     
 15     public static void main(String[] args) 
 16     {
 17         CSVFile csvFile=new CSVFile("e:\\test1.csv");
 18         boolean ret=csvFile.read();
 19         if(ret)
 20         {
 21             csvFile.getDatas();
 22         }
 23         else
 24         {
 25             csvFile.getErrors();
 26         }
 27         System.out.println("over");
 28         int i=0;
 29 
 30     }
 31     
 32     
 33     public CSVFile(String filePath) {
 34         this.cvsFile=new waf.file.File(filePath);
 35     }
 36     
 37 
 38     public boolean hasErrors()
 39     {
 40         int i=this.getErrors().size();
 41         return i>0?true:false;
 42     }
 43     public List<String> getErrors() {
 44         return this.errors;
 45     }
 46 
 47     public void setErrors(List<String> errors) {
 48         this.errors = errors;
 49     }
 50 
 51     public List<List<String>> getDatas() {
 52         return this.datas;
 53     }
 54 
 55     public void setDatas(List<List<String>> datas) {
 56         this.datas = datas;
 57     }
 58 
 59     /**
 60      * @param args
 61      */
 62 
 63 
 64     /**
 65      * 正则表达式。
 66      * @return 匹配csv文件里最小单位的正则表达式,如a,b,c中的a,
 67      * 
 68      */
 69     private static String getRegExp() {
 70         
 71         String SPECIAL_CHAR_A = "[^\",\\n  ]";
 72         String SPECIAL_CHAR_B = "[^\",\\n]";        
 73         String strRegExp = "";
 74         
 75         strRegExp =
 76             "\"(("+ SPECIAL_CHAR_A + "*[,\\n  ])*("+ SPECIAL_CHAR_A + "*\"{2})*)*"+ SPECIAL_CHAR_A + "*\"[  ]*,[  ]*"
 77             +"|"+ SPECIAL_CHAR_B + "*[  ]*,[  ]*"
 78             + "|\"(("+ SPECIAL_CHAR_A + "*[,\\n  ])*("+ SPECIAL_CHAR_A + "*\"{2})*)*"+ SPECIAL_CHAR_A + "*\"[  ]*"
 79             + "|"+ SPECIAL_CHAR_B + "*[  ]*";
 80         
 81         return strRegExp;
 82     }
 83     
 84     
 85     public void readIrregular()
 86     {
 87         this.readIrregular(this.getDatas());
 88     }
 89     public boolean read()
 90     {
 91         List<String> errors=read(this.getDatas());
 92         this.setErrors(errors);
 93         return !this.hasErrors();
 94     }
 95 
 96     public boolean open()
 97     {
 98         return this.cvsFile.openForRead();
 99     }
100     public void close()
101     {
102         cvsFile.close();
103     }
104     private List<String> checkFormat(List<List<String>> fileDataList)
105     {
106         return null;
107     }
108     public void readIrregular(List<List<String>> fileDataList)
109     {
110         String regExp = getRegExp();
111 
112 
113         String strLine = "";
114         String str = "";
115         Pattern pattern = Pattern.compile(regExp);
116 
117         int lineNumber=0;
118         int lastCols=0;
119         while ((strLine = this.cvsFile.readLine()) != null)
120         {
121             lineNumber++;
122             
123             Matcher matcher = pattern.matcher(strLine);
124             List<String> listTemp = new ArrayList<String>();
125             int currCols=0;
126             while(matcher.find()) 
127             {
128                 boolean shouldBreak=false;
129                 currCols++;
130                 str = matcher.group();
131                 str = str.trim();
132                 if (str.endsWith(","))
133                 {
134                     str = str.substring(0, str.length()-1);
135                     str = str.trim();
136                 }
137                 else
138                 {
139                     shouldBreak=true;
140                 }
141                 if (str.startsWith("\"") && str.endsWith("\"")) 
142                 {
143                     str = str.substring(1, str.length()-1);
144                     if (isExisted("\"\"", str)) {
145                         str = str.replaceAll("\"\"", "\"");
146                     }
147                 }
148                 if(fileDataList!=null)
149                 {
150                     listTemp.add(str);
151                 }
152                 if(shouldBreak)
153                 {
154                     break;
155                 }
156 
157             }
158             lastCols=currCols;
159             
160             if(fileDataList!=null)
161             {
162                 fileDataList.add(listTemp);
163             }
164         }        
165     }
166     private List<String> read(List<List<String>> fileDataList) 
167     {
168         List<String> errors=new ArrayList<String>();
169 
170         String regExp = getRegExp();
171 
172 
173         String strLine = "";
174         String str = "";
175         Pattern pattern = Pattern.compile(regExp);
176 
177         int lineNumber=0;
178         int lastCols=0;
179         
180         while ((strLine = this.cvsFile.readLine()) != null)
181         {
182             lineNumber++;
183             
184             List<String> listTemp = new ArrayList<String>();
185             Matcher matcher = pattern.matcher(strLine);
186             
187             int currCols=0;
188             while(matcher.find()) 
189             {
190                 currCols++;
191                 str = matcher.group();
192                 str = str.trim();
193                 if (str.endsWith(","))
194                 {
195                     str = str.substring(0, str.length()-1);
196                     str = str.trim();
197                 }
198                 if (str.startsWith("\"") && str.endsWith("\"")) 
199                 {
200                     str = str.substring(1, str.length()-1);
201                     if (isExisted("\"\"", str)) {
202                         str = str.replaceAll("\"\"", "\"");
203                     }
204                 }
205                 if(fileDataList!=null)
206                 {
207                     listTemp.add(str);
208                 }
209 
210             }
211             if(lineNumber>1)
212             {
213                 if(currCols!=lastCols)
214                 {
215                     errors.add("第"+lineNumber+"列与第"+(lineNumber-1)+"格式不同");
216 //                    System.out.println("第"+lineNumber+"列与第"+(lineNumber-1)+"格式不同");
217                     // 最多只提示100条
218                     if(errors.size()>100)
219                     {
220                         break;
221                     }
222                 }
223             }
224             lastCols=currCols;
225             
226             if(fileDataList!=null)
227             {
228                 fileDataList.add(listTemp);
229             }
230         }
231 
232         return errors;
233     }    
234     
235     static private boolean isExisted(String argChar, String argStr) {
236         
237         boolean blnReturnValue = false;
238         if ((argStr.indexOf(argChar) >= 0)
239                 && (argStr.indexOf(argChar) <= argStr.length())) {
240             blnReturnValue = true;
241         }
242         return blnReturnValue;
243     }
244    
245     /**
246      * csv文件做成<BR/>
247      * 将argList写入argPath路径下的argFileName文件里。
248      *
249      * @param argList  要写入csv文件的数据(List<String[]>)
250      * @param argPath csv文件路径
251      * @param argFileName csv文件名
252      * @param isNewFile 是否覆盖原有文件
253      * @throws IOException
254      * @throws Exception
255      */
256 //    public static void writeCsvFile(List argList, String argPath, String argFileName, boolean isNewFile)
257 //        throws IOException, Exception {
258 //        CsvFileUtil util = new CsvFileUtil();
259 //        // 数据check
260 //        if (argList == null || argList.size() == 0) {
261 //            throw new Exception("没有数据");
262 //        }
263 //        for (int i = 0; i < argList.size(); i++) {
264 //            if (!(argList.get(i) instanceof String[])) {
265 //                throw new Exception("数据格式不对");
266 //            }
267 //        }
268 //        FileWriter fileWriter = null;
269 //        BufferedWriter bufferedWriter = null;
270 //        String strFullFileName = argPath;
271 //        if (strFullFileName.lastIndexOf("\\") == (strFullFileName.length() - 1)) {
272 //            strFullFileName += argFileName;
273 //        } else {
274 //            strFullFileName += "\\" + argFileName;
275 //        }
276 //        File file = new File(strFullFileName);
277 //        // 文件路径check
278 //        if (!file.getParentFile().exists()) {
279 //            file.getParentFile().mkdirs();
280 //        }
281 //        try {
282 //            if (isNewFile) {
283 //                // 覆盖原有文件
284 //                fileWriter = new FileWriter(file);
285 //            } else {
286 //                // 在原有文件上追加数据
287 //                fileWriter = new FileWriter(file, true);
288 //            }
289 //            bufferedWriter = new BufferedWriter(fileWriter);
290 //            for (int i = 0; i < argList.size(); i++) {
291 //                String[] strTemp = (String[]) argList.get(i);
292 //                for (int j = 0; j < strTemp.length; j++) {
293 //                    if (util.isExisted("\"",strTemp[j])) {
294 //                        strTemp[j] = strTemp[j].replaceAll("\"", "\"\"");
295 //                        bufferedWriter.write("\""+strTemp[j]+"\"");
296 //                    } else if (util.isExisted(",",strTemp[j])
297 //                            || util.isExisted("\n",strTemp[j])
298 //                            || util.isExisted(" ",strTemp[j])
299 //                            || util.isExisted("??",strTemp[j])){
300 //                        bufferedWriter.write("\""+strTemp[j]+"\"");
301 //                    } else {
302 //                        bufferedWriter.write(strTemp[j]);
303 //                    }
304 //                    if (j < strTemp.length - 1) {
305 //                        bufferedWriter.write(",");
306 //                    }
307 //                }
308 //                bufferedWriter.newLine();
309 //            }
310 //        } catch (IOException e) {
311 //            e.printStackTrace();
312 //        } finally {
313 //            try {
314 //                if (bufferedWriter != null) {
315 //                    bufferedWriter.close();
316 //                }
317 //                if (fileWriter != null) {
318 //                    fileWriter.close();
319 //                }
320 //            } catch (IOException e) {
321 //                throw e;
322 //            }
323 //        }
324 //    }    
325 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值