如何用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

原文地址:https://www.cnblogs.com/GarfieldEr007/p/5342822.html