Energy of Love  
          日歷
          <2009年8月>
          2627282930311
          2345678
          9101112131415
          16171819202122
          23242526272829
          303112345
          統(tǒng)計(jì)
          • 隨筆 - 70
          • 文章 - 0
          • 評(píng)論 - 80
          • 引用 - 0

          導(dǎo)航

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          搜索

          •  

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

           
          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.File;
          import java.io.FileNotFoundException;
          import java.io.FileReader;
          import java.io.FileWriter;
          import java.io.IOException;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.logging.Level;
          import java.util.logging.Logger;
          import java.util.regex.Matcher;
          import java.util.regex.Pattern;

          /**
           * 
          @author panhf2003
           * 
          @version 2008/09/05,
           
          */

          public class CsvFileUtil
          {
              
              
          /**
               * 構(gòu)造,禁止實(shí)例化
               
          */
              
          private CsvFileUtil()
              {}
              
              
          public static void main(String[] args)
              {
                  
          try
                  {
                      readCsvFile(
          "d:\\ZD_CUSTOMER_VIEW.csv");
                  }
                  
          catch (FileNotFoundException ex)
                  {
                      Logger.getLogger(CsvFileUtil.
          class.getName()).log(Level.SEVERE,
                              
          null, ex);
                  }
                  
          catch (IOException ex)
                  {
                      Logger.getLogger(CsvFileUtil.
          class.getName()).log(Level.SEVERE,
                              
          null, ex);
                  }
              }
              
              
          /**
               * csv文件讀取<BR/> 讀取絕對(duì)路徑為argPath的csv文件數(shù)據(jù),并以List返回。
               * 
               * 
          @param argPath
               *            csv文件絕對(duì)路徑
               * 
          @return csv文件數(shù)據(jù)(List<String[]>)
               * 
          @throws FileNotFoundException
               * 
          @throws IOException
               
          */
              
          public static List<String[]> readCsvFile(String argPath)
                      
          throws FileNotFoundException, IOException
              {
                  CsvFileUtil util 
          = new CsvFileUtil();
                  File cvsFile 
          = new File(argPath);
                  List
          <String[]> list = new ArrayList<String[]>();
                  FileReader fileReader 
          = null;
                  BufferedReader bufferedReader 
          = null;
                  
          try
                  {
                      fileReader 
          = new FileReader(cvsFile);
                      bufferedReader 
          = new BufferedReader(fileReader);
                      String regExp 
          = util.getRegExp();
                      
                      String strLine 
          = "";
                      String str 
          = "";
                      
          while ((strLine = bufferedReader.readLine()) != null)
                      {
                          Pattern pattern 
          = Pattern.compile(regExp);
                          Matcher matcher 
          = pattern.matcher(strLine);
                          List
          <String> listTemp = new ArrayList<String>();
                          
          while (matcher.find())
                          {
                              str 
          = matcher.group();
                              str 
          = str.trim();
                              
          if (str.endsWith(","))
                              {
                                  str 
          = str.substring(0, str.length() - 1);
                                  str 
          = str.trim();
                              }
                              
          if (str.startsWith("\"") && str.endsWith("\""))
                              {
                                  str 
          = str.substring(1, str.length() - 1);
                                  
          if (util.isExisted("\"\"", str))
                                  {
                                      str 
          = str.replaceAll("\"\"""\"");
                                  }
                              }
                              
          if (!"".equals(str))
                              {
                                  System.out.print(str 
          + " ");
                                  listTemp.add(str);
                              }
                          }
                          
          // test
                          System.out.println();
                          list.add((String[]) listTemp
                                  .toArray(
          new String[listTemp.size()]));
                      }
                  }
                  
          catch (FileNotFoundException e)
                  {
                      
          throw e;
                  }
                  
          catch (IOException e)
                  {
                      
          throw e;
                  }
                  
          finally
                  {
                      
          try
                      {
                          
          if (bufferedReader != null)
                          {
                              bufferedReader.close();
                          }
                          
          if (fileReader != null)
                          {
                              fileReader.close();
                          }
                      }
                      
          catch (IOException e)
                      {
                          
          throw e;
                      }
                  }
                  
          return list;
              }
              
              
          /**
               * csv文件做成<BR/> 將argList寫(xiě)入argPath路徑下的argFileName文件里。
               * 
               * 
          @param argList
               *            要寫(xiě)入csv文件的數(shù)據(jù)(List<String[]>)
               * 
          @param argPath
               *            csv文件路徑
               * 
          @param argFileName
               *            csv文件名
               * 
          @param isNewFile
               *            是否覆蓋原有文件
               * 
          @throws IOException
               * 
          @throws Exception
               
          */
              
          public static void writeCsvFile(List<String[]> argList, String argPath,
                      String argFileName, 
          boolean isNewFile) throws IOException,
                      Exception
              {
                  CsvFileUtil util 
          = new CsvFileUtil();
                  
          // 數(shù)據(jù)check
                  if (argList == null || argList.size() == 0)
                  {
                      
          throw new Exception("沒(méi)有數(shù)據(jù)");
                  }
                  
          for (int i = 0; i < argList.size(); i++)
                  {
                      
          if (!(argList.get(i) instanceof String[]))
                      {
                          
          throw new Exception("數(shù)據(jù)格式不對(duì)");
                      }
                  }
                  FileWriter fileWriter 
          = null;
                  BufferedWriter bufferedWriter 
          = null;
                  String strFullFileName 
          = argPath;
                  
          if (strFullFileName.lastIndexOf("\\"== (strFullFileName.length() - 1))
                  {
                      strFullFileName 
          += argFileName;
                  }
                  
          else
                  {
                      strFullFileName 
          += "\\" + argFileName;
                  }
                  File file 
          = new File(strFullFileName);
                  
          // 文件路徑check
                  if (!file.getParentFile().exists())
                  {
                      file.getParentFile().mkdirs();
                  }
                  
          try
                  {
                      
          if (isNewFile)
                      {
                          
          // 覆蓋原有文件
                          fileWriter = new FileWriter(file);
                      }
                      
          else
                      {
                          
          // 在原有文件上追加數(shù)據(jù)
                          fileWriter = new FileWriter(file, true);
                      }
                      bufferedWriter 
          = new BufferedWriter(fileWriter);
                      
          for (int i = 0; i < argList.size(); i++)
                      {
                          String[] strTemp 
          = (String[]) argList.get(i);
                          
          for (int j = 0; j < strTemp.length; j++)
                          {
                              
          if (util.isExisted("\"", strTemp[j]))
                              {
                                  strTemp[j] 
          = strTemp[j].replaceAll("\"""\"\"");
                                  bufferedWriter.write("\"" + strTemp[j] + "\"");
                              }
                              
          else if (util.isExisted(",", strTemp[j])
                                      
          || util.isExisted("\n", strTemp[j])
                                      
          || util.isExisted(" ", strTemp[j])
                                      
          || util.isExisted("??", strTemp[j]))
                              {
                                  bufferedWriter.write(
          "\"" + strTemp[j] + "\"");
                              }
                              
          else
                              {
                                  bufferedWriter.write(strTemp[j]);
                              }
                              
          if (j < strTemp.length - 1)
                              {
                                  bufferedWriter.write(
          ",");
                              }
                          }
                          bufferedWriter.newLine();
                      }
                  }
                  
          catch (IOException e)
                  {
                      e.printStackTrace();
                  }
                  
          finally
                  {
                      
          try
                      {
                          
          if (bufferedWriter != null)
                          {
                              bufferedWriter.close();
                          }
                          
          if (fileWriter != null)
                          {
                              fileWriter.close();
                          }
                      }
                      
          catch (IOException e)
                      {
                          
          throw e;
                      }
                  }
              }
              
              
          /**
               * 
          @param argChar
               * 
          @param argStr
               * 
          @return
               
          */
              
          private boolean isExisted(String argChar, String argStr)
              {
                  
                  
          boolean blnReturnValue = false;
                  
          if ((argStr.indexOf(argChar) >= 0)
                          
          && (argStr.indexOf(argChar) <= argStr.length()))
                  {
                      blnReturnValue 
          = true;
                  }
                  
          return blnReturnValue;
              }
              
              
          /**
               * 正則表達(dá)式。
               * 
               * 
          @return 匹配csv文件里最小單位的正則表達(dá)式。
               
          */
              
          private String getRegExp()
              {
                  StringBuffer strRegExps 
          = new StringBuffer();
                  strRegExps.append(
          "\"((");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*[,\\n  ])*(");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*\"{2})*)*");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*\"[  ]*,[  ]*");
                  strRegExps.append("|");
                  strRegExps.append(SPECIAL_CHAR_B);
                  strRegExps.append(
          "*[  ]*,[  ]*");
                  strRegExps.append(
          "|\"((");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*[,\\n  ])*(");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*\"{2})*)*");
                  strRegExps.append(SPECIAL_CHAR_A);
                  strRegExps.append(
          "*\"[  ]*");
                  strRegExps.append("|");
                  strRegExps.append(SPECIAL_CHAR_B);
                  strRegExps.append(
          "*[  ]*");
                  
          return strRegExps.toString();
              }
              
              
          private static final String SPECIAL_CHAR_A = "[^\",\\n  ]";
              
              
          private static final String SPECIAL_CHAR_B = "[^\",\\n]";
          }
          posted on 2009-08-10 21:21 不高興 閱讀(295) 評(píng)論(0)  編輯  收藏 所屬分類: Java
           
          Copyright © 不高興 Powered by: 博客園 模板提供:滬江博客
          主站蜘蛛池模板: 海安县| 老河口市| 浠水县| 仪征市| 高邮市| 南靖县| 汉寿县| 锦州市| 泸州市| 大足县| 大港区| 福建省| 嘉兴市| 石城县| 嘉定区| 寿宁县| 鲜城| 阿拉善左旗| 娄底市| 阿坝| 堆龙德庆县| 澄迈县| 嘉禾县| 曲沃县| 南溪县| 井冈山市| 巨鹿县| 甘德县| 潜山县| 谢通门县| 辽源市| 高阳县| 遂昌县| 怀集县| 固阳县| 晋中市| 忻州市| 景德镇市| 古田县| 和平区| 天津市|