Java读取CSV的常用方法

原链接  :http://blog.csdn.net/hantiannan/article/details/6756347


 

Java读取CSV的常用方法

分类: JAVA   18人阅读  评论(0)  收藏  举报

在项目开发中,我们经常需要读取csv的内容的操作。读取的逻辑并不复杂。主要是对有换行的,逗号,引号的处理恰当的话就没问题了。

下面作为memo,把在项目中的读取方法拷贝了过来。有了下面的这些方法,在CSV的读取和输出的时候都非常方便。

  1. package com.han.csv.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.util.ArrayList;  
  7.   
  8. public class CSVFileUtil {  
  9.     // CSV文件编码  
  10.     public static final String ENCODE = "UTF-8";  
  11.   
  12.     private FileInputStream fis = null;  
  13.     private InputStreamReader isw = null;  
  14.     private BufferedReader br = null;  
  15.   
  16.      
  17.     public CSVFileUtil(String filename) throws Exception {  
  18.         fis = new FileInputStream(filename);  
  19.         isw = new InputStreamReader(fis, ENCODE);  
  20.         br = new BufferedReader(isw);  
  21.     }  
  22.   
  23.     // ==========以下是公开方法=============================  
  24.     /** 
  25.      * 从CSV文件流中读取一个CSV行。 
  26.      * 
  27.      * @throws Exception 
  28.      */  
  29.     public String readLine() throws Exception {  
  30.   
  31.         StringBuffer readLine = new StringBuffer();  
  32.         boolean bReadNext = true;  
  33.   
  34.         while (bReadNext) {  
  35.             //  
  36.             if (readLine.length() > 0) {  
  37.                 readLine.append("\r\n");  
  38.             }  
  39.             // 一行  
  40.             String strReadLine = br.readLine();  
  41.   
  42.             // readLine is Null  
  43.             if (strReadLine == null) {  
  44.                 return null;  
  45.             }  
  46.             readLine.append(strReadLine);  
  47.   
  48.             // 如果双引号是奇数的时候继续读取。考虑有换行的是情况。  
  49.             if (countChar(readLine.toString(), '"'0) % 2 == 1) {  
  50.                 bReadNext = true;  
  51.             } else {  
  52.                 bReadNext = false;  
  53.             }  
  54.         }  
  55.         return readLine.toString();  
  56.     }  
  57.   
  58.     /** 
  59.      *把CSV文件的一行转换成字符串数组。指定数组长度,不够长度的部分设置为null。 
  60.      */  
  61.     public static String[] fromCSVLine(String source, int size) {  
  62.         ArrayList tmpArray = fromCSVLinetoArray(source);  
  63.         if (size < tmpArray.size()) {  
  64.             size = tmpArray.size();  
  65.         }  
  66.         String[] rtnArray = new String[size];  
  67.         tmpArray.toArray(rtnArray);  
  68.         return rtnArray;  
  69.     }  
  70.   
  71.     /** 
  72.      * 把CSV文件的一行转换成字符串数组。不指定数组长度。 
  73.      */  
  74.     public static ArrayList fromCSVLinetoArray(String source) {  
  75.         if (source == null || source.length() == 0) {  
  76.             return new ArrayList();  
  77.         }  
  78.         int currentPosition = 0;  
  79.         int maxPosition = source.length();  
  80.         int nextComma = 0;  
  81.         ArrayList rtnArray = new ArrayList();  
  82.         while (currentPosition < maxPosition) {  
  83.             nextComma = nextComma(source, currentPosition);  
  84.             rtnArray.add(nextToken(source, currentPosition, nextComma));  
  85.             currentPosition = nextComma + 1;  
  86.             if (currentPosition == maxPosition) {  
  87.                 rtnArray.add("");  
  88.             }  
  89.         }  
  90.         return rtnArray;  
  91.     }  
  92.   
  93.   
  94.     /** 
  95.      * 把字符串类型的数组转换成一个CSV行。(输出CSV文件的时候用) 
  96.      */  
  97.     public static String toCSVLine(String[] strArray) {  
  98.         if (strArray == null) {  
  99.             return "";  
  100.         }  
  101.         StringBuffer cvsLine = new StringBuffer();  
  102.         for (int idx = 0; idx < strArray.length; idx++) {  
  103.             String item = addQuote(strArray[idx]);  
  104.             cvsLine.append(item);  
  105.             if (strArray.length - 1 != idx) {  
  106.                 cvsLine.append(',');  
  107.             }  
  108.         }  
  109.         return cvsLine.toString();  
  110.     }  
  111.   
  112.     /** 
  113.      * 字符串类型的List转换成一个CSV行。(输出CSV文件的时候用) 
  114.      */  
  115.     public static String toCSVLine(ArrayList strArrList) {  
  116.         if (strArrList == null) {  
  117.             return "";  
  118.         }  
  119.         String[] strArray = new String[strArrList.size()];  
  120.         for (int idx = 0; idx < strArrList.size(); idx++) {  
  121.             strArray[idx] = (String) strArrList.get(idx);  
  122.         }  
  123.         return toCSVLine(strArray);  
  124.     }  
  125.   
  126.     // ==========以下是内部使用的方法=============================  
  127.     /** 
  128.      *计算指定文字的个数。 
  129.      * 
  130.      * @param str 文字列 
  131.      * @param c 文字 
  132.      * @param start  开始位置 
  133.      * @return 个数 
  134.      */  
  135.     private int countChar(String str, char c, int start) {  
  136.         int i = 0;  
  137.         int index = str.indexOf(c, start);  
  138.         return index == -1 ? i : countChar(str, c, index + 1) + 1;  
  139.     }  
  140.   
  141.     /** 
  142.      * 查询下一个逗号的位置。 
  143.      * 
  144.      * @param source 文字列 
  145.      * @param st  检索开始位置 
  146.      * @return 下一个逗号的位置。 
  147.      */  
  148.     private static int nextComma(String source, int st) {  
  149.         int maxPosition = source.length();  
  150.         boolean inquote = false;  
  151.         while (st < maxPosition) {  
  152.             char ch = source.charAt(st);  
  153.             if (!inquote && ch == ',') {  
  154.                 break;  
  155.             } else if ('"' == ch) {  
  156.                 inquote = !inquote;  
  157.             }  
  158.             st++;  
  159.         }  
  160.         return st;  
  161.     }  
  162.   
  163.     /** 
  164.      * 取得下一个字符串 
  165.      */  
  166.     private static String nextToken(String source, int st, int nextComma) {  
  167.         StringBuffer strb = new StringBuffer();  
  168.         int next = st;  
  169.         while (next < nextComma) {  
  170.             char ch = source.charAt(next++);  
  171.             if (ch == '"') {  
  172.                 if ((st + 1 < next && next < nextComma) && (source.charAt(next) == '"')) {  
  173.                     strb.append(ch);  
  174.                     next++;  
  175.                 }  
  176.             } else {  
  177.                 strb.append(ch);  
  178.             }  
  179.         }  
  180.         return strb.toString();  
  181.     }  
  182.   
  183.     /** 
  184.      * 在字符串的外侧加双引号。如果该字符串的内部有双引号的话,把"转换成""。 
  185.      * 
  186.      * @param item  字符串 
  187.      * @return 处理过的字符串 
  188.      */  
  189.     private static String addQuote(String item) {  
  190.         if (item == null || item.length() == 0) {  
  191.             return "\"\"";  
  192.         }  
  193.         StringBuffer sb = new StringBuffer();  
  194.         sb.append('"');  
  195.         for (int idx = 0; idx < item.length(); idx++) {  
  196.             char ch = item.charAt(idx);  
  197.             if ('"' == ch) {  
  198.                 sb.append("\"\"");  
  199.             } else {  
  200.                 sb.append(ch);  
  201.             }  
  202.         }  
  203.         sb.append('"');  
  204.         return sb.toString();  
  205.     }  
  206. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值