如何用Java解析CSV文件


首先看一下csv文件的規則:
csv(Comma Separate Values)文件即逗號分隔符文件,它是一種文本文件,可以直接以文本打開,以逗號分隔。windows默認用excel打開。它的格式包括以下幾點(它的格式最好就看excel是如何解析的。):

①每條記錄占一行;
②以逗號為分隔符;
③逗號前后的空格會被忽略;
④字段中包含有逗號,該字段必須用雙引號括起來;
⑤字段中包含有換行符,該字段必須用雙引號括起來;
⑥字段前后包含有空格,該字段必須用雙引號括起來;
⑦字段中的雙引號用兩個雙引號表示;
⑧字段中如果有雙引號,該字段必須用雙引號括起來;
⑨第一條記錄,可以是字段名;

⑩以上提到的逗號和雙引號均為半角字符。

下面給出一種解析方法,來自:http://blog.csdn.net/studyvcmfc/article/details/6232770,原文中有一些bug,經過修改,測試ok的代碼如下:

該解析算法的解析規則與excel或者wps大致相同。另外包含去掉注釋的方法。

構建方法該類包含一個構建方法,參數為要讀取的csv文件的文件名(包含絕對路徑)。

普通方法:

① getVContent():一個得到當前行的值向量的方法。如果調用此方法前未調用readCSVNextRecord方法,則將返回Null。
② getLineContentVector():一個得到下一行值向量的方法。如果該方法返回Null,則說明已經讀到文件末尾。
③ close():關閉流。該方法為調用該類后應該被最后調用的方法。
④ readCSVNextRecord():該方法讀取csv文件的下一行,如果該方法已經讀到了文件末尾,則返回false;
⑤ readAtomString(String):該方法返回csv文件邏輯一行的第一個值,和該邏輯行第一個值后面的內容,如果該內容以逗號開始,則已經去掉了該逗號。這兩個值以一個二維數組的方法返回。
⑥ isQuoteAdjacent(String):判斷一個給定字符串的引號是否兩兩相鄰。如果兩兩相鄰,返回真。如果該字符串不包含引號,也返回真。
⑦ readCSVFileTitle():該方法返回csv文件中的第一行——該行不以#號開始(包括正常解析后的#號),且該行不為空
解析接口代碼:

  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. }    

其實呢。。。。作為一個標准,CSV的解析應該更簡單,這里大放送,JVM的CSV解析結合:

http://ostermiller.org/utils/CSV.html

經測試,如下實例是最好用的:
https://github.com/segasai/SAI-CAS/tree/master/src/sai_cas/input/csv

 

from: http://jacoxu.com/?p=1490


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM