csv文件

来源:互联网 发布:淘宝情趣用品店知乎 编辑:程序博客网 时间:2024/05/16 09:08
  1. import java.io.BufferedReader;   
  2. import java.io.FileInputStream;   
  3. import java.io.IOException;   
  4. import java.io.InputStreamReader;   
  5. import java.util.ArrayList;   
  6. import java.util.List;   
  7. import java.util.regex.Matcher;   
  8. import java.util.regex.Pattern;   
  9.   
  10. /*  
  11.  * 文件规则  
  12.  * Microsoft的格式是最简单的。以逗号分隔的值要么是“纯粹的”(仅仅包含在括号之前), 
  13.  * 要么是在双引号之间(这时数据中的双引号以一对双引号表示)。 
  14.  * Ten Thousand,10000, 2710 ,,"10,000","It's ""10 Grand"", baby",10K 
  15.  * 这一行包含七个字段(fields): 
  16.  *  Ten Thousand  
  17.  *  10000  
  18.  *   2710   
  19.  *  空字段  
  20.  *  10,000  
  21.  *  It's "10 Grand", baby 
  22.  *  10K  
  23.  * 每条记录占一行  
  24.  * 以逗号为分隔符  
  25.  * 逗号前后的空格会被忽略  
  26.  * 字段中包含有逗号,该字段必须用双引号括起来。如果是全角的没有问题。 
  27.  * 字段中包含有换行符,该字段必须用双引号括起来 
  28.  * 字段前后包含有空格,该字段必须用双引号括起来 
  29.  * 字段中的双引号用两个双引号表示  
  30.  * 字段中如果有双引号,该字段必须用双引号括起来 
  31.  * 第一条记录,可以是字段名  
  32.  */  
  33.   
  34. public class CSVAnalysis {   
  35.     private InputStreamReader fr = null;   
  36.     private BufferedReader br = null;   
  37.   
  38.     public CSVAnalysis(String f) throws IOException {   
  39.         fr = new InputStreamReader(new FileInputStream(f));   
  40.     }   
  41.   
  42.     /**  
  43.      * 解析csv文件 到一个list中 
  44.      * 每个单元个为一个String类型记录,每一行为一个list。 
  45.      * 再将所有的行放到一个总list中 
  46.      * @return  
  47.      * @throws IOException 
  48.      */  
  49.     public List<List<String>> readCSVFile() throws IOException {   
  50.         br = new BufferedReader(fr);   
  51.         String rec = null;//一行  
  52.         String str;//一个单元格  
  53.         List<List<String>> listFile = new ArrayList<List<String>>();   
  54.         try {              
  55.             //读取一行  
  56.             while ((rec = br.readLine()) != null) {   
  57.                 Pattern pCells = Pattern   
  58.                         .compile("(/"[^/"]*(/"{2})*[^/"]*/")*[^,]*,");   
  59.                 Matcher mCells = pCells.matcher(rec);   
  60.                 List<String> cells = new ArrayList<String>();//每行记录一个list  
  61.                 //读取每个单元格  
  62.                 while (mCells.find()) {   
  63.                     str = mCells.group();   
  64.                     str = str.replaceAll(   
  65.                             "(?sm)/"?([^/"]*(/"{2})*[^/"]*)/"?.*,""$1");   
  66.                     str = str.replaceAll("(?sm)(/"(/"))""$2");   
  67.                     cells.add(str);   
  68.                 }   
  69.                 listFile.add(cells);   
  70.             }              
  71.         } catch (Exception e) {   
  72.             e.printStackTrace();   
  73.         } finally {   
  74.             if (fr != null) {   
  75.                 fr.close();   
  76.             }   
  77.             if (br != null) {   
  78.                 br.close();   
  79.             }   
  80.         }   
  81.         return listFile;   
  82.     }   
  83.   
  84.     public static void main(String[] args) throws Throwable {   
  85.         CSVAnalysis parser = new CSVAnalysis("c:/test2.csv");   
  86.         parser.readCSVFile();   
  87.     }   
  88. }  
[java] view plaincopyprint?
  1. import java.io.BufferedReader;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.regex.Matcher;  
  8. import java.util.regex.Pattern;  
  9.   
  10. /* 
  11.  * 文件规则 
  12.  * Microsoft的格式是最简单的。以逗号分隔的值要么是“纯粹的”(仅仅包含在括号之前), 
  13.  * 要么是在双引号之间(这时数据中的双引号以一对双引号表示)。 
  14.  * Ten Thousand,10000, 2710 ,,"10,000","It's ""10 Grand"", baby",10K 
  15.  * 这一行包含七个字段(fields): 
  16.  *  Ten Thousand 
  17.  *  10000 
  18.  *   2710  
  19.  *  空字段 
  20.  *  10,000 
  21.  *  It's "10 Grand", baby 
  22.  *  10K 
  23.  * 每条记录占一行 
  24.  * 以逗号为分隔符 
  25.  * 逗号前后的空格会被忽略 
  26.  * 字段中包含有逗号,该字段必须用双引号括起来。如果是全角的没有问题。 
  27.  * 字段中包含有换行符,该字段必须用双引号括起来 
  28.  * 字段前后包含有空格,该字段必须用双引号括起来 
  29.  * 字段中的双引号用两个双引号表示 
  30.  * 字段中如果有双引号,该字段必须用双引号括起来 
  31.  * 第一条记录,可以是字段名 
  32.  */  
  33.   
  34. public class CSVAnalysis {  
  35.     private InputStreamReader fr = null;  
  36.     private BufferedReader br = null;  
  37.   
  38.     public CSVAnalysis(String f) throws IOException {  
  39.         fr = new InputStreamReader(new FileInputStream(f));  
  40.     }  
  41.   
  42.     /** 
  43.      * 解析csv文件 到一个list中 
  44.      * 每个单元个为一个String类型记录,每一行为一个list。 
  45.      * 再将所有的行放到一个总list中 
  46.      * @return 
  47.      * @throws IOException 
  48.      */  
  49.     public List<List<String>> readCSVFile() throws IOException {  
  50.         br = new BufferedReader(fr);  
  51.         String rec = null;//一行  
  52.         String str;//一个单元格   
  53.         List<List<String>> listFile = new ArrayList<List<String>>();  
  54.         try {             
  55.             //读取一行   
  56.             while ((rec = br.readLine()) != null) {  
  57.                 Pattern pCells = Pattern  
  58.                         .compile("(/"[^/"]*(/"{2})*[^/"]*/")*[^,]*,");  
  59.                 Matcher mCells = pCells.matcher(rec);  
  60.                 List<String> cells = new ArrayList<String>();//每行记录一个list  
  61.                 //读取每个单元格   
  62.                 while (mCells.find()) {  
  63.                     str = mCells.group();  
  64.                     str = str.replaceAll(  
  65.                             "(?sm)/"?([^/"]*(/"{2})*[^/"]*)/"?.*,", "$1");  
  66.                     str = str.replaceAll("(?sm)(/"(/"))""$2");  
  67.                     cells.add(str);  
  68.                 }  
  69.                 listFile.add(cells);  
  70.             }             
  71.         } catch (Exception e) {  
  72.             e.printStackTrace();  
  73.         } finally {  
  74.             if (fr != null) {  
  75.                 fr.close();  
  76.             }  
  77.             if (br != null) {  
  78.                 br.close();  
  79.             }  
  80.         }  
  81.         return listFile;  
  82.     }  
  83.   
  84.     public static void main(String[] args) throws Throwable {  
  85.         CSVAnalysis parser = new CSVAnalysis("c:/test2.csv");  
  86.         parser.readCSVFile();  
  87.     }  
  88. }  

 

二。

在解析csv文件之前,先来看看什么是csv文件以及csv文件的格式。

csv(Comma Separate Values)文件即逗号分隔符文件,它是一种文本文件,可以直接以文本打开,以逗号分隔。windows默认用excel打开。它的格式包括以下几点(它的格式最好就看excel是如何解析的。):

①每条记录占一行;
②以逗号为分隔符;
③逗号前后的空格会被忽略;
④字段中包含有逗号,该字段必须用双引号括起来;
⑤字段中包含有换行符,该字段必须用双引号括起来;
⑥字段前后包含有空格,该字段必须用双引号括起来;
⑦字段中的双引号用两个双引号表示;
⑧字段中如果有双引号,该字段必须用双引号括起来;
⑨第一条记录,可以是字段名;

⑩以上提到的逗号和双引号均为半角字符。

下面通过正则表达式和java解析csv文件。

首先给出匹配csv文件的一个最小单位数据的正则表达式(如:1,2,3是csv文件的一行数据,则1,是该csv文件的一个最小单位数据):

"(([^",/n  ]*[,/n  ])*([^",/n  ]*"{2})*)*[^",/n  ]*"[  ]*,[  ]*|[^",/n]*[  ]*,[  ]*|"(([^",/n  ]*[,/n  ])*([^",/n  ]*"{2})*)*[^",/n  ]*"[  ]*|[^",/n]*[  ]*

 

下面是解析文件的java代码:

Java代码 复制代码 收藏代码
  1. import java.io.BufferedReader;   
  2. import java.io.BufferedWriter;   
  3. import java.io.File;   
  4. import java.io.FileNotFoundException;   
  5. import java.io.FileReader;   
  6. import java.io.FileWriter;   
  7. import java.io.IOException;   
  8. import java.util.ArrayList;   
  9. import java.util.List;   
  10. import java.util.logging.Level;   
  11. import java.util.logging.Logger;   
  12. import java.util.regex.Matcher;   
  13. import java.util.regex.Pattern;   
  14.   
  15. /**  
  16.  * @author  panhf2003 
  17.  * @version 2008/09/05, 
  18.  */  
  19.   
  20. public class CsvFileUtil {   
  21.   
  22.      private static final String SPECIAL_CHAR_A = "[^/",//n  ]";   
  23.      private static final String SPECIAL_CHAR_B = "[^/",//n]";   
  24.        
  25.     /**  
  26.      * 构造,禁止实例化  
  27.      */  
  28.     private CsvFileUtil() {   
  29.     }   
  30.   
  31.     public static void main(String[] args) {   
  32.   
  33.         // test  
  34.         try {   
  35.             readCsvFile("e://test1.csv");   
  36.         } catch (FileNotFoundException ex) {   
  37.             Logger.getLogger(CsvFileUtil.class.getName()).log(Level.SEVERE, null, ex);   
  38.         } catch (IOException ex) {   
  39.             Logger.getLogger(CsvFileUtil.class.getName()).log(Level.SEVERE, null, ex);   
  40.         }   
  41.     }   
  42.     /**  
  43.      * csv文件读取<BR/>  
  44.      * 读取绝对路径为argPath的csv文件数据,并以List返回。 
  45.      *  
  46.      * @param argPath csv文件绝对路径 
  47.      * @return csv文件数据(List<String[]>) 
  48.      * @throws FileNotFoundException 
  49.      * @throws IOException 
  50.      */  
  51.     public static List readCsvFile(String argPath) throws FileNotFoundException, IOException {   
  52.         CsvFileUtil util = new CsvFileUtil();   
  53.         File cvsFile = new File(argPath);   
  54.         List list = new ArrayList();   
  55.         FileReader fileReader = null;   
  56.         BufferedReader bufferedReader = null;   
  57.         try {   
  58.             fileReader = new FileReader(cvsFile);   
  59.             bufferedReader = new BufferedReader(fileReader);   
  60.             String regExp = util.getRegExp();   
  61.   
  62.             // test  
  63.             System.out.println(regExp);   
  64.             String strLine = "";   
  65.             String str = "";   
  66.             while ((strLine = bufferedReader.readLine()) != null) {   
  67.                 Pattern pattern = Pattern.compile(regExp);   
  68.                 Matcher matcher = pattern.matcher(strLine);   
  69.                 List listTemp = new ArrayList();   
  70.                 while(matcher.find()) {   
  71.                     str = matcher.group();   
  72.                     str = str.trim();   
  73.                     if (str.endsWith(",")){   
  74.                         str = str.substring(0, str.length()-1);   
  75.                         str = str.trim();   
  76.                     }   
  77.                     if (str.startsWith("/"") && str.endsWith("/"")) {   
  78.                         str = str.substring(1, str.length()-1);   
  79.                         if (util.isExisted("/"/"", str)) {   
  80.                             str = str.replaceAll("/"/"""/"");   
  81.                         }   
  82.                     }   
  83.                     if (!"".equals(str)) {   
  84.                         //test  
  85.                         System.out.print(str+" ");   
  86.                         listTemp.add(str);   
  87.                     }   
  88.                 }   
  89.                 //test  
  90.                 System.out.println();   
  91.                 list.add((String[]) listTemp.toArray(new String[listTemp.size()]));   
  92.             }   
  93.         } catch (FileNotFoundException e) {   
  94.             throw e;   
  95.         } catch (IOException e) {   
  96.             throw e;   
  97.         } finally {   
  98.             try {   
  99.                 if (bufferedReader != null) {   
  100.                     bufferedReader.close();   
  101.                 }   
  102.                 if (fileReader != null) {   
  103.                     fileReader.close();   
  104.                 }   
  105.             } catch (IOException e) {   
  106.                 throw e;   
  107.             }   
  108.         }   
  109.         return list;   
  110.     }   
  111.        
  112.     /**  
  113.      * csv文件做成<BR/>  
  114.      * 将argList写入argPath路径下的argFileName文件里。 
  115.      *  
  116.      * @param argList  要写入csv文件的数据(List<String[]>) 
  117.      * @param argPath csv文件路径 
  118.      * @param argFileName csv文件名 
  119.      * @param isNewFile 是否覆盖原有文件 
  120.      * @throws IOException 
  121.      * @throws Exception 
  122.      */  
  123.     public static void writeCsvFile(List argList, String argPath, String argFileName, boolean isNewFile)   
  124.         throws IOException, Exception {   
  125.         CsvFileUtil util = new CsvFileUtil();   
  126.         // 数据check  
  127.         if (argList == null || argList.size() == 0) {   
  128.             throw new Exception("没有数据");   
  129.         }   
  130.         for (int i = 0; i < argList.size(); i++) {   
  131.             if (!(argList.get(i) instanceof String[])) {   
  132.                 throw new Exception("数据格式不对");   
  133.             }   
  134.         }   
  135.         FileWriter fileWriter = null;   
  136.         BufferedWriter bufferedWriter = null;   
  137.         String strFullFileName = argPath;   
  138.         if (strFullFileName.lastIndexOf("//") == (strFullFileName.length() - 1)) {   
  139.             strFullFileName += argFileName;   
  140.         } else {   
  141.             strFullFileName += "//" + argFileName;   
  142.         }   
  143.         File file = new File(strFullFileName);   
  144.         // 文件路径check  
  145.         if (!file.getParentFile().exists()) {   
  146.             file.getParentFile().mkdirs();   
  147.         }   
  148.         try {   
  149.             if (isNewFile) {   
  150.                 // 覆盖原有文件  
  151.                 fileWriter = new FileWriter(file);   
  152.             } else {   
  153.                 // 在原有文件上追加数据  
  154.                 fileWriter = new FileWriter(file, true);   
  155.             }   
  156.             bufferedWriter = new BufferedWriter(fileWriter);   
  157.             for (int i = 0; i < argList.size(); i++) {   
  158.                 String[] strTemp = (String[]) argList.get(i);   
  159.                 for (int j = 0; j < strTemp.length; j++) {   
  160.                     if (util.isExisted("/"",strTemp[j])) {   
  161.                         strTemp[j] = strTemp[j].replaceAll("/"""/"/"");   
  162.                         bufferedWriter.write("/""+strTemp[j]+"/"");   
  163.                     } else if (util.isExisted(",",strTemp[j])   
  164.                             || util.isExisted("/n",strTemp[j])   
  165.                             || util.isExisted(" ",strTemp[j])   
  166.                             || util.isExisted("��",strTemp[j])){   
  167.                         bufferedWriter.write("/""+strTemp[j]+"/"");   
  168.                     } else {   
  169.                         bufferedWriter.write(strTemp[j]);   
  170.                     }   
  171.                     if (j < strTemp.length - 1) {   
  172.                         bufferedWriter.write(",");   
  173.                     }   
  174.                 }   
  175.                 bufferedWriter.newLine();   
  176.             }   
  177.         } catch (IOException e) {   
  178.             e.printStackTrace();   
  179.         } finally {   
  180.             try {   
  181.                 if (bufferedWriter != null) {   
  182.                     bufferedWriter.close();   
  183.                 }   
  184.                 if (fileWriter != null) {   
  185.                     fileWriter.close();   
  186.                 }   
  187.             } catch (IOException e) {   
  188.                 throw e;   
  189.             }   
  190.         }   
  191.     }   
  192.        
  193.     /**  
  194.      * @param argChar 
  195.      * @param argStr  
  196.      * @return  
  197.      */  
  198.     private boolean isExisted(String argChar, String argStr) {   
  199.            
  200.         boolean blnReturnValue = false;   
  201.         if ((argStr.indexOf(argChar) >= 0)   
  202.                 && (argStr.indexOf(argChar) <= argStr.length())) {   
  203.             blnReturnValue = true;   
  204.         }   
  205.         return blnReturnValue;   
  206.     }   
  207.        
  208.     /**  
  209.      * 正则表达式。  
  210.      * @return 匹配csv文件里最小单位的正则表达式。 
  211.      */  
  212.     private String getRegExp() {   
  213.            
  214.         String strRegExp = "";   
  215.            
  216.         strRegExp =   
  217.             "/"(("+ SPECIAL_CHAR_A + "*[,//n  ])*("+ SPECIAL_CHAR_A + "*/"{2})*)*"+ SPECIAL_CHAR_A + "*/"[  ]*,[  ]*"  
  218.             +"|"+ SPECIAL_CHAR_B + "*[  ]*,[  ]*"  
  219.             + "|/"(("+ SPECIAL_CHAR_A + "*[,//n  ])*("+ SPECIAL_CHAR_A + "*/"{2})*)*"+ SPECIAL_CHAR_A + "*/"[  ]*"  
  220.             + "|"+ SPECIAL_CHAR_B + "*[  ]*";   
  221.            
  222.         return strRegExp;   
  223.     }   
  224.        
  225.       
  226. }  
[java] view plaincopyprint?
  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileReader;  
  6. import java.io.FileWriter;  
  7. import java.io.IOException;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10. import java.util.logging.Level;  
  11. import java.util.logging.Logger;  
  12. import java.util.regex.Matcher;  
  13. import java.util.regex.Pattern;  
  14.   
  15. /** 
  16.  * @author  panhf2003 
  17.  * @version 2008/09/05, 
  18.  */  
  19.   
  20. public class CsvFileUtil {  
  21.   
  22.      private static final String SPECIAL_CHAR_A = "[^/",//n  ]";  
  23.      private static final String SPECIAL_CHAR_B = "[^/",//n]";  
  24.       
  25.     /** 
  26.      * 构造,禁止实例化 
  27.      */  
  28.     private CsvFileUtil() {  
  29.     }  
  30.   
  31.     public static void main(String[] args) {  
  32.   
  33.         // test   
  34.         try {  
  35.             readCsvFile("e://test1.csv");  
  36.         } catch (FileNotFoundException ex) {  
  37.             Logger.getLogger(CsvFileUtil.class.getName()).log(Level.SEVERE, null, ex);  
  38.         } catch (IOException ex) {  
  39.             Logger.getLogger(CsvFileUtil.class.getName()).log(Level.SEVERE, null, ex);  
  40.         }  
  41.     }  
  42.     /** 
  43.      * csv文件读取<BR/> 
  44.      * 读取绝对路径为argPath的csv文件数据,并以List返回。 
  45.      * 
  46.      * @param argPath csv文件绝对路径 
  47.      * @return csv文件数据(List<String[]>) 
  48.      * @throws FileNotFoundException 
  49.      * @throws IOException 
  50.      */  
  51.     public static List readCsvFile(String argPath) throws FileNotFoundException, IOException {  
  52.         CsvFileUtil util = new CsvFileUtil();  
  53.         File cvsFile = new File(argPath);  
  54.         List list = new ArrayList();  
  55.         FileReader fileReader = null;  
  56.         BufferedReader bufferedReader = null;  
  57.         try {  
  58.             fileReader = new FileReader(cvsFile);  
  59.             bufferedReader = new BufferedReader(fileReader);  
  60.             String regExp = util.getRegExp();  
  61.   
  62.             // test   
  63.             System.out.println(regExp);  
  64.             String strLine = "";  
  65.             String str = "";  
  66.             while ((strLine = bufferedReader.readLine()) != null) {  
  67.                 Pattern pattern = Pattern.compile(regExp);  
  68.                 Matcher matcher = pattern.matcher(strLine);  
  69.                 List listTemp = new ArrayList();  
  70.                 while(matcher.find()) {  
  71.                     str = matcher.group();  
  72.                     str = str.trim();  
  73.                     if (str.endsWith(",")){  
  74.                         str = str.substring(0, str.length()-1);  
  75.                         str = str.trim();  
  76.                     }  
  77.                     if (str.startsWith("/"") && str.endsWith("/"")) {  
  78.                         str = str.substring(1, str.length()-1);  
  79.                         if (util.isExisted("/"/"", str)) {  
  80.                             str = str.replaceAll("/"/"""/"");  
  81.                         }  
  82.                     }  
  83.                     if (!"".equals(str)) {  
  84.                         //test   
  85.                         System.out.print(str+" ");  
  86.                         listTemp.add(str);  
  87.                     }  
  88.                 }  
  89.                 //test   
  90.                 System.out.println();  
  91.                 list.add((String[]) listTemp.toArray(new String[listTemp.size()]));  
  92.             }  
  93.         } catch (FileNotFoundException e) {  
  94.             throw e;  
  95.         } catch (IOException e) {  
  96.             throw e;  
  97.         } finally {  
  98.             try {  
  99.                 if (bufferedReader != null) {  
  100.                     bufferedReader.close();  
  101.                 }  
  102.                 if (fileReader != null) {  
  103.                     fileReader.close();  
  104.                 }  
  105.             } catch (IOException e) {  
  106.                 throw e;  
  107.             }  
  108.         }  
  109.         return list;  
  110.     }  
  111.       
  112.     /** 
  113.      * csv文件做成<BR/> 
  114.      * 将argList写入argPath路径下的argFileName文件里。 
  115.      * 
  116.      * @param argList  要写入csv文件的数据(List<String[]>) 
  117.      * @param argPath csv文件路径 
  118.      * @param argFileName csv文件名 
  119.      * @param isNewFile 是否覆盖原有文件 
  120.      * @throws IOException 
  121.      * @throws Exception 
  122.      */  
  123.     public static void writeCsvFile(List argList, String argPath, String argFileName, boolean isNewFile)  
  124.         throws IOException, Exception {  
  125.         CsvFileUtil util = new CsvFileUtil();  
  126.         // 数据check   
  127.         if (argList == null || argList.size() == 0) {  
  128.             throw new Exception("没有数据");  
  129.         }  
  130.         for (int i = 0; i < argList.size(); i++) {  
  131.             if (!(argList.get(i) instanceof String[])) {  
  132.                 throw new Exception("数据格式不对");  
  133.             }  
  134.         }  
  135.         FileWriter fileWriter = null;  
  136.         BufferedWriter bufferedWriter = null;  
  137.         String strFullFileName = argPath;  
  138.         if (strFullFileName.lastIndexOf("//") == (strFullFileName.length() - 1)) {  
  139.             strFullFileName += argFileName;  
  140.         } else {  
  141.             strFullFileName += "//" + argFileName;  
  142.         }  
  143.         File file = new File(strFullFileName);  
  144.         // 文件路径check   
  145.         if (!file.getParentFile().exists()) {  
  146.             file.getParentFile().mkdirs();  
  147.         }  
  148.         try {  
  149.             if (isNewFile) {  
  150.                 // 覆盖原有文件   
  151.                 fileWriter = new FileWriter(file);  
  152.             } else {  
  153.                 // 在原有文件上追加数据   
  154.                 fileWriter = new FileWriter(file, true);  
  155.             }  
  156.             bufferedWriter = new BufferedWriter(fileWriter);  
  157.             for (int i = 0; i < argList.size(); i++) {  
  158.                 String[] strTemp = (String[]) argList.get(i);  
  159.                 for (int j = 0; j < strTemp.length; j++) {  
  160.                     if (util.isExisted("/"",strTemp[j])) {  
  161.                         strTemp[j] = strTemp[j].replaceAll("/"", "/"/"");  
  162.                         bufferedWriter.write("/""+strTemp[j]+"/"");  
  163.                     } else if (util.isExisted(",",strTemp[j])  
  164.                             || util.isExisted("/n",strTemp[j])  
  165.                             || util.isExisted(" ",strTemp[j])  
  166.                             || util.isExisted("��",strTemp[j])){  
  167.                         bufferedWriter.write("/""+strTemp[j]+"/"");  
  168.                     } else {  
  169.                         bufferedWriter.write(strTemp[j]);  
  170.                     }  
  171.                     if (j < strTemp.length - 1) {  
  172.                         bufferedWriter.write(",");  
  173.                     }  
  174.                 }  
  175.                 bufferedWriter.newLine();  
  176.             }  
  177.         } catch (IOException e) {  
  178.             e.printStackTrace();  
  179.         } finally {  
  180.             try {  
  181.                 if (bufferedWriter != null) {  
  182.                     bufferedWriter.close();  
  183.                 }  
  184.                 if (fileWriter != null) {  
  185.                     fileWriter.close();  
  186.                 }  
  187.             } catch (IOException e) {  
  188.                 throw e;  
  189.             }  
  190.         }  
  191.     }  
  192.       
  193.     /** 
  194.      * @param argChar 
  195.      * @param argStr 
  196.      * @return 
  197.      */  
  198.     private boolean isExisted(String argChar, String argStr) {  
  199.           
  200.         boolean blnReturnValue = false;  
  201.         if ((argStr.indexOf(argChar) >= 0)  
  202.                 && (argStr.indexOf(argChar) <= argStr.length())) {  
  203.             blnReturnValue = true;  
  204.         }  
  205.         return blnReturnValue;  
  206.     }  
  207.       
  208.     /** 
  209.      * 正则表达式。 
  210.      * @return 匹配csv文件里最小单位的正则表达式。 
  211.      */  
  212.     private String getRegExp() {  
  213.           
  214.         String strRegExp = "";  
  215.           
  216.         strRegExp =  
  217.             "/"(("+ SPECIAL_CHAR_A + "*[,//n  ])*("+ SPECIAL_CHAR_A + "*/"{2})*)*"+ SPECIAL_CHAR_A + "*/"[  ]*,[  ]*"  
  218.             +"|"+ SPECIAL_CHAR_B + "*[  ]*,[  ]*"  
  219.             + "|/"(("+ SPECIAL_CHAR_A + "*[,//n  ])*("+ SPECIAL_CHAR_A + "*/"{2})*)*"+ SPECIAL_CHAR_A + "*/"[  ]*"  
  220.             + "|"+ SPECIAL_CHAR_B + "*[  ]*";  
  221.           
  222.         return strRegExp;  
  223.     }  
  224.       
  225.      
  226. }  

 

三。

 

该解析算法的解析规则与excel或者wps大致相同。另外包含去掉注释的方法。

构建方法该类包含一个构建方法,参数为要读取的csv文件的文件名(包含绝对路径)。

普通方法:

getVContent():一个得到当前行的值向量的方法。如果调用此方法前未调用readCSVNextRecord方法,则将返回Null。

getLineContentVector():一个得到下一行值向量的方法。如果该方法返回Null,则说明已经读到文件末尾。

close():关闭流。该方法为调用该类后应该被最后调用的方法。

readCSVNextRecord():该方法读取csv文件的下一行,如果该方法已经读到了文件末尾,则返回false;

readAtomString(String):该方法返回csv文件逻辑一行的第一个值,和该逻辑行第一个值后面的内容,如果该内容以逗号开始,则已经去掉了该逗号。这两个值以一个二维数组的方法返回。

isQuoteAdjacent(String):判断一个给定字符串的引号是否两两相邻。如果两两相邻,返回真。如果该字符串不包含引号,也返回真。

readCSVFileTitle():该方法返回csv文件中的第一行——该行不以#号开始(包括正常解析后的#号),且该行不为空

Java代码 复制代码 收藏代码
  1. import java.io.BufferedReader;   
  2. import java.io.FileNotFoundException;   
  3. import java.io.FileReader;   
  4. import java.io.IOException;   
  5. import java.util.Vector;   
  6.   
  7. public class CsvParse {   
  8.     //声明读取流   
  9.     private BufferedReader inStream = null;   
  10.     //声明返回向量   
  11.     private Vector<String> vContent = null;   
  12.   
  13.     /**  
  14.      * 构建方法,参数为csv文件名<br> 
  15.      * 如果没有找到文件,则抛出异常<br> 
  16.      * 如果抛出异常,则不能进行页面的文件读取操作 
  17.      */  
  18.     public CsvParse(String csvFileName) throws FileNotFoundException {   
  19.         inStream = new BufferedReader(new FileReader(csvFileName));   
  20.     }   
  21.   
  22.     /**  
  23.      * 返回已经读取到的一行的向量  
  24.      * @return vContent 
  25.      */  
  26.     public Vector<String> getVContent() {   
  27.         return this.vContent;   
  28.     }   
  29.   
  30.     /**  
  31.      * 读取下一行,并把该行的内容填充入向量中<br> 
  32.      * 返回该向量<br>  
  33.      * @return vContent 装载了下一行的向量 
  34.      * @throws IOException 
  35.      * @throws Exception 
  36.      */  
  37.     public Vector<String> getLineContentVector() throws IOException, Exception {   
  38.         if (this.readCSVNextRecord()) {   
  39.             return this.vContent;   
  40.         }   
  41.         return null;   
  42.     }   
  43.   
  44.     /**  
  45.      * 关闭流  
  46.      */  
  47.     public void close() {   
  48.         if (inStream != null) {   
  49.             try {   
  50.                 inStream.close();   
  51.             } catch (IOException e) {   
  52.                 // TODO Auto-generated catch block  
  53.                 e.printStackTrace();   
  54.             }   
  55.         }   
  56.     }   
  57.   
  58.     /**  
  59.      * 调用此方法时应该确认该类已经被正常初始化<br> 
  60.      * 该方法用于读取csv文件的下一个逻辑行<br> 
  61.      * 读取到的内容放入向量中<br> 
  62.      * 如果该方法返回了false,则可能是流未被成功初始化<br> 
  63.      * 或者已经读到了文件末尾<br> 
  64.      * 如果发生异常,则不应该再进行读取 
  65.      * @return 返回值用于标识是否读到文件末尾 
  66.      * @throws Exception 
  67.      */  
  68.     public boolean readCSVNextRecord() throws IOException, Exception {   
  69.         //如果流未被初始化则返回false  
  70.         if (inStream == null) {   
  71.             return false;   
  72.         }   
  73.         //如果结果向量未被初始化,则初始化  
  74.         if (vContent == null) {   
  75.             vContent = new Vector<String>();   
  76.         }   
  77.         //移除向量中以前的元素  
  78.         vContent.removeAllElements();   
  79.         //声明逻辑行  
  80.         String logicLineStr = "";   
  81.         //用于存放读到的行  
  82.         StringBuilder strb = new StringBuilder();   
  83.         //声明是否为逻辑行的标志,初始化为false  
  84.         boolean isLogicLine = false;   
  85.         try {   
  86.             while (!isLogicLine) {   
  87.                 String newLineStr = inStream.readLine();   
  88.                 if (newLineStr == null) {   
  89.                     strb = null;   
  90.                     vContent = null;   
  91.                     isLogicLine = true;   
  92.                     break;   
  93.                 }   
  94.                 if (newLineStr.startsWith("#")) {   
  95.                     // 去掉注释  
  96.                     continue;   
  97.                 }   
  98.                 if (!strb.toString().equals("")) {   
  99.                     strb.append("/r/n");   
  100.                 }   
  101.                 strb.append(newLineStr);   
  102.                 String oldLineStr = strb.toString();   
  103.                 if (oldLineStr.indexOf(",") == -1) {   
  104.                     // 如果该行未包含逗号  
  105.                     if (containsNumber(oldLineStr, "/"") % 2 == 0) {   
  106.                         // 如果包含偶数个引号  
  107.                         isLogicLine = true;   
  108.                         break;   
  109.                     } else {   
  110.                         if (oldLineStr.startsWith("/"")) {   
  111.                             if (oldLineStr.equals("/"")) {   
  112.                                 continue;   
  113.                             } else {   
  114.                                 String tempOldStr = oldLineStr.substring(1);   
  115.                                 if (isQuoteAdjacent(tempOldStr)) {   
  116.                                     // 如果剩下的引号两两相邻,则不是一行  
  117.                                     continue;   
  118.                                 } else {   
  119.                                     // 否则就是一行  
  120.                                     isLogicLine = true;   
  121.                                     break;   
  122.                                 }   
  123.                             }   
  124.                         }   
  125.                     }   
  126.                 } else {   
  127.                     // quotes表示复数的quote  
  128.                     String tempOldLineStr = oldLineStr.replace("/"/"""");   
  129.                     int lastQuoteIndex = tempOldLineStr.lastIndexOf("/"");   
  130.                     if (lastQuoteIndex == 0) {   
  131.                         continue;   
  132.                     } else if (lastQuoteIndex == -1) {   
  133.                         isLogicLine = true;   
  134.                         break;   
  135.                     } else {   
  136.                         tempOldLineStr = tempOldLineStr.replace("/",/"""");   
  137.                         lastQuoteIndex = tempOldLineStr.lastIndexOf("/"");   
  138.                         if (lastQuoteIndex == 0) {   
  139.                             continue;   
  140.                         }   
  141.                         if (tempOldLineStr.charAt(lastQuoteIndex - 1) == ',') {   
  142.                             continue;   
  143.                         } else {   
  144.                             isLogicLine = true;   
  145.                             break;   
  146.                         }   
  147.                     }   
  148.                 }   
  149.             }   
  150.         } catch (IOException ioe) {   
  151.             ioe.printStackTrace();   
  152.             //发生异常时关闭流  
  153.             if (inStream != null) {   
  154.                 inStream.close();   
  155.             }   
  156.             throw ioe;   
  157.         } catch (Exception e) {   
  158.             e.printStackTrace();   
  159.             //发生异常时关闭流  
  160.             if (inStream != null) {   
  161.                 inStream.close();   
  162.             }   
  163.             throw e;   
  164.         }   
  165.         if (strb == null) {   
  166.             // 读到行尾时为返回  
  167.             return false;   
  168.         }   
  169.         //提取逻辑行  
  170.         logicLineStr = strb.toString();   
  171.         if (logicLineStr != null) {   
  172.             //拆分逻辑行,把分离出来的原子字符串放入向量中  
  173.             while (!logicLineStr.equals("")) {   
  174.                 String[] ret = readAtomString(logicLineStr);   
  175.                 String atomString = ret[0];   
  176.                 logicLineStr = ret[1];   
  177.                 vContent.add(atomString);   
  178.             }   
  179.         }   
  180.         return true;   
  181.     }   
  182.   
  183.     /**  
  184.      * 读取一个逻辑行中的第一个字符串,并返回剩下的字符串<br> 
  185.      * 剩下的字符串中不包含第一个字符串后面的逗号<br> 
  186.      * @param lineStr 一个逻辑行 
  187.      * @return 第一个字符串和剩下的逻辑行内容 
  188.      */  
  189.     public String[] readAtomString(String lineStr) {   
  190.         String atomString = "";//要读取的原子字符串  
  191.         String orgString = "";//保存第一次读取下一个逗号时的未经任何处理的字符串  
  192.         String[] ret = new String[2];//要返回到外面的数组  
  193.         boolean isAtom = false;//是否是原子字符串的标志  
  194.         String[] commaStr = lineStr.split(",");   
  195.         while (!isAtom) {   
  196.             for (String str : commaStr) {   
  197.                 if (!atomString.equals("")) {   
  198.                     atomString = atomString + ",";   
  199.                 }   
  200.                 atomString = atomString + str;   
  201.                 orgString = atomString;   
  202.                 if (!isQuoteContained(atomString)) {   
  203.                     // 如果字符串中不包含引号,则为正常,返回  
  204.                     isAtom = true;   
  205.                     break;   
  206.                 } else {   
  207.                     if (!atomString.startsWith("/"")) {   
  208.                         // 如果字符串不是以引号开始,则表示不转义,返回  
  209.                         isAtom = true;   
  210.                         break;   
  211.                     } else if (atomString.startsWith("/"")) {   
  212.                         // 如果字符串以引号开始,则表示转义  
  213.                         if (containsNumber(atomString, "/"") % 2 == 0) {   
  214.                             // 如果含有偶数个引号  
  215.                             String temp = atomString;   
  216.                             if (temp.endsWith("/"")) {   
  217.                                 temp = temp.replace("/"/"""");   
  218.                                 if (temp.equals("")) {   
  219.                                     // 如果temp为空  
  220.                                     atomString = "";   
  221.                                     isAtom = true;   
  222.                                     break;   
  223.                                 } else {   
  224.                                     // 如果temp不为空,则去掉前后引号  
  225.                                     temp = temp.substring(1, temp   
  226.                                             .lastIndexOf("/""));   
  227.                                     if (temp.indexOf("/"") > -1) {   
  228.                                         // 去掉前后引号和相邻引号之后,若temp还包含有引号  
  229.                                         // 说明这些引号是单个单个出现的  
  230.                                         temp = atomString;   
  231.                                         temp = temp.substring(1);   
  232.                                         temp = temp.substring(0, temp   
  233.                                                 .indexOf("/""))   
  234.                                                 + temp.substring(temp   
  235.                                                         .indexOf("/"") + 1);   
  236.                                         atomString = temp;   
  237.                                         isAtom = true;   
  238.                                         break;   
  239.                                     } else {   
  240.                                         // 正常的csv文件  
  241.                                         temp = atomString;   
  242.                                         temp = temp.substring(1, temp   
  243.                                                 .lastIndexOf("/""));   
  244.                                         temp = temp.replace("/"/"""/"");   
  245.                                         atomString = temp;   
  246.                                         isAtom = true;   
  247.                                         break;   
  248.                                     }   
  249.                                 }   
  250.                             } else {   
  251.                                 // 如果不是以引号结束,则去掉前两个引号  
  252.                                 temp = temp.substring(1, temp.indexOf('/"'1))   
  253.                                         + temp   
  254.                                                 .substring(temp   
  255.                                                         .indexOf('/"'1) + 1);   
  256.                                 atomString = temp;   
  257.                                 isAtom = true;   
  258.                                 break;   
  259.                             }   
  260.                         } else {   
  261.                             // 如果含有奇数个引号  
  262.                             // TODO 处理奇数个引号的情况  
  263.                             if (!atomString.equals("/"")) {   
  264.                                 String tempAtomStr = atomString.substring(1);   
  265.                                 if (!isQuoteAdjacent(tempAtomStr)) {   
  266.                                     // 这里做的原因是,如果判断前面的字符串不是原子字符串的时候就读取第一个取到的字符串  
  267.                                     // 后面取到的字符串不计入该原子字符串  
  268.                                     tempAtomStr = atomString.substring(1);   
  269.                                     int tempQutoIndex = tempAtomStr   
  270.                                             .indexOf("/"");   
  271.                                     // 这里既然有奇数个quto,所以第二个quto肯定不是最后一个  
  272.                                     tempAtomStr = tempAtomStr.substring(0,   
  273.                                             tempQutoIndex)   
  274.                                             + tempAtomStr   
  275.                                                     .substring(tempQutoIndex + 1);   
  276.                                     atomString = tempAtomStr;   
  277.                                     isAtom = true;   
  278.                                     break;   
  279.                                 }   
  280.                             }   
  281.                         }   
  282.                     }   
  283.                 }   
  284.             }   
  285.         }   
  286.         //先去掉之前读取的原字符串的母字符串  
  287.         if (lineStr.length() > orgString.length()) {   
  288.             lineStr = lineStr.substring(orgString.length());   
  289.         } else {   
  290.             lineStr = "";   
  291.         }   
  292.         //去掉之后,判断是否以逗号开始,如果以逗号开始则去掉逗号  
  293.         if (lineStr.startsWith(",")) {   
  294.             if (lineStr.length() > 1) {   
  295.                 lineStr = lineStr.substring(1);   
  296.             } else {   
  297.                 lineStr = "";   
  298.             }   
  299.         }   
  300.         ret[0] = atomString;   
  301.         ret[1] = lineStr;   
  302.         return ret;   
  303.     }   
  304.   
  305.     /**  
  306.      * 该方法取得父字符串中包含指定字符串的数量<br> 
  307.      * 如果父字符串和字字符串任意一个为空值,则返回零 
  308.      * @param parentStr 
  309.      * @param parameter 
  310.      * @return  
  311.      */  
  312.     public int containsNumber(String parentStr, String parameter) {   
  313.         int containNumber = 0;   
  314.         if (parentStr == null || parentStr.equals("")) {   
  315.             return 0;   
  316.         }   
  317.         if (parameter == null || parameter.equals("")) {   
  318.             return 0;   
  319.         }   
  320.         for (int i = 0; i < parentStr.length(); i++) {   
  321.             i = parentStr.indexOf(parameter, i);   
  322.             if (i > -1) {   
  323.                 i = i + parameter.length();   
  324.                 i--;   
  325.                 containNumber = containNumber + 1;   
  326.             } else {   
  327.                 break;   
  328.             }   
  329.         }   
  330.         return containNumber;   
  331.     }   
  332.   
  333.     /**  
  334.      * 该方法用于判断给定的字符串中的引号是否相邻<br> 
  335.      * 如果相邻返回真,否则返回假<br> 
  336.      *  
  337.      * @param p_String 
  338.      * @return  
  339.      */  
  340.     public boolean isQuoteAdjacent(String p_String) {   
  341.         boolean ret = false;   
  342.         String temp = p_String;   
  343.         temp = temp.replace("/"/"""");   
  344.         if (temp.indexOf("/"") == -1) {   
  345.             ret = true;   
  346.         }   
  347.         // TODO 引号相邻  
  348.         return ret;   
  349.     }   
  350.   
  351.     /**  
  352.      * 该方法用于判断给定的字符串中是否包含引号<br> 
  353.      * 如果字符串为空或者不包含返回假,包含返回真<br> 
  354.      *  
  355.      * @param p_String 
  356.      * @return  
  357.      */  
  358.     public boolean isQuoteContained(String p_String) {   
  359.         boolean ret = false;   
  360.         if (p_String == null || p_String.equals("")) {   
  361.             return false;   
  362.         }   
  363.         if (p_String.indexOf("/"") > -1) {   
  364.             ret = true;   
  365.         }   
  366.         return ret;   
  367.     }   
  368.   
  369.     /**  
  370.      * 读取文件标题  
  371.      *  
  372.      * @return 正确读取文件标题时返回 true,否则返回 false 
  373.      * @throws Exception 
  374.      * @throws IOException 
  375.      */  
  376.     public boolean readCSVFileTitle() throws IOException, Exception {   
  377.         String strValue = "";   
  378.         boolean isLineEmpty = true;   
  379.         do {   
  380.             if (!readCSVNextRecord()) {   
  381.                 return false;   
  382.             }   
  383.             if (vContent.size() > 0) {   
  384.                 strValue = (String) vContent.get(0);   
  385.             }   
  386.             for (String str : vContent) {   
  387.                 if (str != null && !str.equals("")) {   
  388.                     isLineEmpty = false;   
  389.                     break;   
  390.                 }   
  391.             }   
  392.             // csv 文件中前面几行以 # 开头为注释行  
  393.         } while (strValue.trim().startsWith("#") || isLineEmpty);   
  394.         return true;   
  395.     }   
  396. }  
原创粉丝点击