论坛首页 Java企业应用论坛

Java CSV格式文件处理

浏览 8751 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2012-01-03  

Java CSV格式文件处理

 

导出 用流写出即可。导出cvs文件。

 

 

java code:

	/**
	 * 获取csv 文件中的内容
	 * @param path csv的文件位置
	 * @return 内容集合
	 * @throws Exception
	 */
	public List<String[]> CSVLoad(String path) throws Exception {
		List<String[]> list = new ArrayList<String[]>();
		BufferedReader br = new BufferedReader(new FileReader(path));
		while (br.ready()) {
			// CSV格式文件为逗号分隔符文件,这里根据逗号切分
			String[] rows = br.readLine().split(",");
			list.add(rows);
		}
		return list;
	}

	/**
	 * 创建csv格式字符
	 * @param list 数据集合
	 * @return csv格式字符
	 * @throws Exception
	 */
	public StringBuffer CSVSave(List<String[]> list) throws Exception {
		StringBuffer sb = new StringBuffer();
		for (String[] strs : list) {
			for (int i = 0; i < strs.length; i++) {
				sb.append(strs[i] + ",");
			}
			sb.append("\r\n");
		}
		return sb;
	}

 

   发表时间:2012-01-04  
这样处理明显不行,有想过,如果文本信息包括","咋处理吗?
0 请登录后投票
   发表时间:2012-01-04  
1.List感觉不如用Map好,创建csv格式字符时不能区分头部和数据部分。
2.如果数据列中出现的内容带有"\r\n"你将如何拆解。
3.一般我采用http://sourceforge.net/projects/javacsv/files/
0 请登录后投票
   发表时间:2012-01-05  

特殊情况还是有必要处理一下的,以下是经过三次修订的结果

 

里面的方法readFileToList我就不贴内容了,把注释贴出来就可以了,哈哈

 

     List<String> readFileToList(File file) 注释
    /**
     * 使用默认字符集读取文件内容按行返回字符串集合
     * @param file 文件
     * @return List<String> 文件内容集合
     * @throws IOException
     */
 

 

/**
 * CSV文件中需要转义的字符集正则表达式
 */
public static final String CSV_REGEX = ".*([\"|\\,|\\n|\\r]|(\\r\\n)|(\\n\\r)).*";

/**
 * 将普通字符串转换为符合CSV格式的字符串
 * @param str 普通字符串
 * @return 符合CSV格式的字符串
 */
public static String toCSVString(String str)
{
    str = str.replaceAll("\"", "\"\"");
    Pattern p = Pattern.compile(CSV_REGEX, Pattern.DOTALL);
    Matcher m = p.matcher(str);
    
    if(m.matches())
    {
        str = "\"" + str + "\"";
    }
    
    return str;
}

/**
 * 解析CSV文件
 * @param file 目标CSV文件
 * @return 解析结果:List<String[]>的每一个元素为一行,String[]的每一个元素为一个单元格
 * @throws IOException
 */
public static List<String[]> parseCSVFile(File file) throws IOException
{
    List<String> fileDatas = readFileToList(file);
    List<String[]> csvDatas = new ArrayList<String[]>();
    List<String> lineDatas = null;
    StringBuilder fragment = null;
    int index = 0;
    
    for(String line: fileDatas)
    {
        index = 0;
        
        if(fragment == null)
        {
            lineDatas = new ArrayList<String>();
        }
        
        for(String cell: line.split(",", -1))
        {
            if(fragment == null)
            {
                //完整,无特殊字符
                if(!cell.startsWith("\""))
                {
                    lineDatas.add(cell.replaceAll("\"\"", "\""));
                }
                //完整,有特殊字符
                else if(cell.endsWith("\"") && countLastDoubleQuotes(cell) % 2 == 1)
                {
                    cell = cell.substring(1, cell.length() - 1);
                    lineDatas.add(cell.replaceAll("\"\"", "\""));
                }
                //不完整,有特殊字符
                else
                {
                    fragment = new StringBuilder(cell);
                }
            }
            else
            {
                fragment.append(index == 0? '\n': ',');
                fragment.append(cell);
                
                //完整,有特殊字符
                if(cell.endsWith("\"") && countLastDoubleQuotes(cell) % 2 == 1)
                {
                    lineDatas.add(fragment.substring(1, fragment.length() - 1).replaceAll("\"\"", "\""));
                    fragment = null;
                }
            }
            
            index++;
        }
        
        if(fragment != null)
        {
            continue;
        }
        else
        {
            csvDatas.add(lineDatas.toArray(new String[lineDatas.size()]));
        }
    }
    
    return csvDatas;
}
 
0 请登录后投票
   发表时间:2012-01-06  
http://opencsv.sourceforge.net/  现成的类库,简单易用
0 请登录后投票
   发表时间:2012-01-06  
建议采用类库
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics