java读取csv文件 .

CSV其实就是COMMA SEPARATED VALUE的缩写。
在开发中用Java操作csv文件有专门的的API叫javacsv.jar

javacsv.jar下载地址:
http://sourceforge.net/project/showfiles.php?group_id=33066

 


下面演示一段操作代码仅供参考:

 

Java代码 复制代码  收藏代码
  1. package com.syc.test.bean;   
  2.   
  3. public class ReslutBean {   
  4.     String help_keyword_id;   
  5.     String name;   
  6.   
  7.     public String getHelp_keyword_id() {   
  8.         return help_keyword_id;   
  9.     }   
  10.   
  11.     public void setHelp_keyword_id(String help_keyword_id) {   
  12.         this.help_keyword_id = help_keyword_id;   
  13.     }   
  14.   
  15.     public String getName() {   
  16.         return name;   
  17.     }   
  18.   
  19.     public void setName(String name) {   
  20.         this.name = name;   
  21.     }   
  22.   
  23. }  
  1. package com.syc.test.bean;  
  2.   
  3. public class ReslutBean {  
  4.     String help_keyword_id;  
  5.     String name;  
  6.   
  7.     public String getHelp_keyword_id() {  
  8.         return help_keyword_id;  
  9.     }  
  10.   
  11.     public void setHelp_keyword_id(String help_keyword_id) {  
  12.         this.help_keyword_id = help_keyword_id;  
  13.     }  
  14.   
  15.     public String getName() {  
  16.         return name;  
  17.     }  
  18.   
  19.     public void setName(String name) {  
  20.         this.name = name;  
  21.     }  
  22.   
  23. }  
package com.syc.test.bean;

public class ReslutBean {
	String help_keyword_id;
	String name;

	public String getHelp_keyword_id() {
		return help_keyword_id;
	}

	public void setHelp_keyword_id(String help_keyword_id) {
		this.help_keyword_id = help_keyword_id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

Java代码 复制代码  收藏代码
  1. package com.syc.test.javaCSV;   
  2.   
  3. import java.io.IOException;   
  4. import java.nio.charset.Charset;   
  5. import java.util.ArrayList;   
  6. import java.util.List;   
  7.   
  8. import com.csvreader.CsvReader;   
  9. import com.csvreader.CsvWriter;   
  10. import com.syc.test.DAO.ConnectionDB;   
  11. import com.syc.test.bean.ReslutBean;   
  12.   
  13. public class Java2CSV {   
  14.     /**  
  15.      * @param args  
  16.      * @throws Exception  
  17.      */  
  18.     public static void main(String[] args) throws Exception {   
  19.         // 从获取将要写入csv文件的结果集   
  20.         List<ReslutBean> list = new ArrayList<ReslutBean>();   
  21.         list = ConnectionDB.querySQL();   
  22.   
  23.         // 预组装csv文件内容标题行   
  24.         String[][] data = new String[list.size() + 1][2];   
  25.         data[0][0] = "Help_keyword_id";   
  26.         data[0][1] = "Name";   
  27.   
  28.         // 预组装csv文件内容   
  29.         int len = list.size();   
  30.         for (int i = 0; i < len; i++) {   
  31.             data[i + 1][0] = list.get(i).getHelp_keyword_id();   
  32.             data[i + 1][1] = list.get(i).getName();   
  33.         }   
  34.   
  35.         writerCsv("e://c测试.csv", data);   
  36.         readerCsv("e://c测试.csv");   
  37.     }   
  38.   
  39.     /**  
  40.      * 读取csv  
  41.      *   
  42.      * @param csvFilePath  
  43.      * @throws Exception  
  44.      */  
  45.     public static void readerCsv(String csvFilePath) throws Exception {   
  46.   
  47.         CsvReader reader = new CsvReader(csvFilePath, ',',   
  48.                 Charset.forName("GBK"));// shift_jis日语字体,utf-8  
  49.         reader.readHeaders();   
  50.         String[] headers = reader.getHeaders();   
  51.   
  52.         List<Object[]> list = new ArrayList<Object[]>();   
  53.         while (reader.readRecord()) {   
  54.             list.add(reader.getValues());   
  55.         }   
  56.         Object[][] datas = new String[list.size()][];   
  57.         for (int i = 0; i < list.size(); i++) {   
  58.             datas[i] = list.get(i);   
  59.         }   
  60.   
  61.         /*  
  62.          * 以下输出  
  63.          */  
  64.   
  65.         for (int i = 0; i < headers.length; i++) {   
  66.             System.out.print(headers[i] + "\t");   
  67.         }   
  68.         System.out.println("");   
  69.   
  70.         for (int i = 0; i < datas.length; i++) {   
  71.             Object[] data = datas[i]; // 取出一组数据  
  72.             for (int j = 0; j < data.length; j++) {   
  73.                 Object cell = data[j];   
  74.                 System.out.print(cell + "\t");   
  75.             }   
  76.             System.out.println("");   
  77.         }   
  78.     }   
  79.   
  80.     /**  
  81.      * 写入csv  
  82.      *   
  83.      * @param csvFilePath文件名路径  
  84.      *            +文件名字  
  85.      * @param data数据项  
  86.      */  
  87.     public static void writerCsv(String csvFilePath, String[][] data) {   
  88.   
  89.         CsvWriter writer = null;   
  90.         try {   
  91.             writer = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));// shift_jis日语字体,utf-8  
  92.   
  93.             for (int i = 0; i < data.length; i++) {   
  94.                 writer.writeRecord(data[i]);   
  95.             }   
  96.         } catch (IOException e) {   
  97.             e.printStackTrace();   
  98.         } finally {   
  99.             writer.close();   
  100.         }   
  101.     }   
  102. }  
  1. package com.syc.test.javaCSV;  
  2.   
  3. import java.io.IOException;  
  4. import java.nio.charset.Charset;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.csvreader.CsvReader;  
  9. import com.csvreader.CsvWriter;  
  10. import com.syc.test.DAO.ConnectionDB;  
  11. import com.syc.test.bean.ReslutBean;  
  12.   
  13. public class Java2CSV {  
  14.     /** 
  15.      * @param args 
  16.      * @throws Exception 
  17.      */  
  18.     public static void main(String[] args) throws Exception {  
  19.         // 从获取将要写入csv文件的结果集   
  20.         List<ReslutBean> list = new ArrayList<ReslutBean>();  
  21.         list = ConnectionDB.querySQL();  
  22.   
  23.         // 预组装csv文件内容标题行   
  24.         String[][] data = new String[list.size() + 1][2];  
  25.         data[0][0] = "Help_keyword_id";  
  26.         data[0][1] = "Name";  
  27.   
  28.         // 预组装csv文件内容   
  29.         int len = list.size();  
  30.         for (int i = 0; i < len; i++) {  
  31.             data[i + 1][0] = list.get(i).getHelp_keyword_id();  
  32.             data[i + 1][1] = list.get(i).getName();  
  33.         }  
  34.   
  35.         writerCsv("e://c测试.csv", data);  
  36.         readerCsv("e://c测试.csv");  
  37.     }  
  38.   
  39.     /** 
  40.      * 读取csv 
  41.      *  
  42.      * @param csvFilePath 
  43.      * @throws Exception 
  44.      */  
  45.     public static void readerCsv(String csvFilePath) throws Exception {  
  46.   
  47.         CsvReader reader = new CsvReader(csvFilePath, ',',  
  48.                 Charset.forName("GBK"));// shift_jis日语字体,utf-8   
  49.         reader.readHeaders();  
  50.         String[] headers = reader.getHeaders();  
  51.   
  52.         List<Object[]> list = new ArrayList<Object[]>();  
  53.         while (reader.readRecord()) {  
  54.             list.add(reader.getValues());  
  55.         }  
  56.         Object[][] datas = new String[list.size()][];  
  57.         for (int i = 0; i < list.size(); i++) {  
  58.             datas[i] = list.get(i);  
  59.         }  
  60.   
  61.         /* 
  62.          * 以下输出 
  63.          */  
  64.   
  65.         for (int i = 0; i < headers.length; i++) {  
  66.             System.out.print(headers[i] + "\t");  
  67.         }  
  68.         System.out.println("");  
  69.   
  70.         for (int i = 0; i < datas.length; i++) {  
  71.             Object[] data = datas[i]; // 取出一组数据   
  72.             for (int j = 0; j < data.length; j++) {  
  73.                 Object cell = data[j];  
  74.                 System.out.print(cell + "\t");  
  75.             }  
  76.             System.out.println("");  
  77.         }  
  78.     }  
  79.   
  80.     /** 
  81.      * 写入csv 
  82.      *  
  83.      * @param csvFilePath文件名路径 
  84.      *            +文件名字 
  85.      * @param data数据项 
  86.      */  
  87.     public static void writerCsv(String csvFilePath, String[][] data) {  
  88.   
  89.         CsvWriter writer = null;  
  90.         try {  
  91.             writer = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));// shift_jis日语字体,utf-8   
  92.   
  93.             for (int i = 0; i < data.length; i++) {  
  94.                 writer.writeRecord(data[i]);  
  95.             }  
  96.         } catch (IOException e) {  
  97.             e.printStackTrace();  
  98.         } finally {  
  99.             writer.close();  
  100.         }  
  101.     }  
  102. }  
package com.syc.test.javaCSV;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.syc.test.DAO.ConnectionDB;
import com.syc.test.bean.ReslutBean;

public class Java2CSV {
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// 从获取将要写入csv文件的结果集
		List<ReslutBean> list = new ArrayList<ReslutBean>();
		list = ConnectionDB.querySQL();

		// 预组装csv文件内容标题行
		String[][] data = new String[list.size() + 1][2];
		data[0][0] = "Help_keyword_id";
		data[0][1] = "Name";

		// 预组装csv文件内容
		int len = list.size();
		for (int i = 0; i < len; i++) {
			data[i + 1][0] = list.get(i).getHelp_keyword_id();
			data[i + 1][1] = list.get(i).getName();
		}

		writerCsv("e://c测试.csv", data);
		readerCsv("e://c测试.csv");
	}

	/**
	 * 读取csv
	 * 
	 * @param csvFilePath
	 * @throws Exception
	 */
	public static void readerCsv(String csvFilePath) throws Exception {

		CsvReader reader = new CsvReader(csvFilePath, ',',
				Charset.forName("GBK"));// shift_jis日语字体,utf-8
		reader.readHeaders();
		String[] headers = reader.getHeaders();

		List<Object[]> list = new ArrayList<Object[]>();
		while (reader.readRecord()) {
			list.add(reader.getValues());
		}
		Object[][] datas = new String[list.size()][];
		for (int i = 0; i < list.size(); i++) {
			datas[i] = list.get(i);
		}

		/*
		 * 以下输出
		 */

		for (int i = 0; i < headers.length; i++) {
			System.out.print(headers[i] + "\t");
		}
		System.out.println("");

		for (int i = 0; i < datas.length; i++) {
			Object[] data = datas[i]; // 取出一组数据
			for (int j = 0; j < data.length; j++) {
				Object cell = data[j];
				System.out.print(cell + "\t");
			}
			System.out.println("");
		}
	}

	/**
	 * 写入csv
	 * 
	 * @param csvFilePath文件名路径
	 *            +文件名字
	 * @param data数据项
	 */
	public static void writerCsv(String csvFilePath, String[][] data) {

		CsvWriter writer = null;
		try {
			writer = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));// shift_jis日语字体,utf-8

			for (int i = 0; i < data.length; i++) {
				writer.writeRecord(data[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.close();
		}
	}
}

  

 

当然你还可以用supecsv 或者 opencsv啦。

先下载javacsv2.0.zip的文件,解压后,把javacsv.jar 添加到项目中。

 

官方下载地址:
http://sourceforge.net/project/showfiles.php?group_id=33066

API地址:

http://javacsv.sourceforge.net/
简单的操作代码:

Java代码 复制代码  收藏代码
  1. import java.io.IOException;   
  2. import java.nio.charset.Charset;   
  3. import java.util.ArrayList;   
  4. import com.csvreader.CsvReader;   
  5. import com.csvreader.CsvWriter;   
  6.     
  7. public class DB2ExportCsv   
  8. {   
  9.     /**  
  10.     * 读取CSV文件  
  11.     */  
  12.     public void  readCsv(){   
  13.         try {       
  14.                 ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据  
  15.                 String csvFilePath = "D:/log/Alarm20101125.csv";   
  16.                 CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("SJIS"));    //一般用这编码读就可以了      
  17.                     
  18.                 reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。  
  19.                     
  20.                 while(reader.readRecord()){ //逐行读入除表头的数据      
  21.                     csvList.add(reader.getValues());   
  22.                 }               
  23.                 reader.close();   
  24.                     
  25.                 for(int row=0;row<csvList.size();row++){   
  26.                      String  cell = csvList.get(row)[0]; //取得第row行第0列的数据  
  27.                      System.out.println(cell);   
  28.                 }        
  29.             } catch (Exception ex) {   
  30.                     System.out.println(ex);   
  31.                 }   
  32.     }   
  33.        
  34.     /**  
  35.      * 写入CSV文件  
  36.      */  
  37.     public static void WriteCsv(){   
  38.         try {   
  39.                 String csvFilePath = "D:/log/Alarm20101125.csv";   
  40.                 CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));   
  41.                 String[] contents = {"告警信息","非法操作","没有权限","操作失败"};                       
  42.                 wr.writeRecord(contents);   
  43.                 wr.close();   
  44.          } catch (IOException e) {   
  45.             e.printStackTrace();   
  46.          }   
  47.     }   
  48. }  
  1. import java.io.IOException;  
  2. import java.nio.charset.Charset;  
  3. import java.util.ArrayList;  
  4. import com.csvreader.CsvReader;  
  5. import com.csvreader.CsvWriter;  
  6.    
  7. public class DB2ExportCsv  
  8. {  
  9.     /** 
  10.     * 读取CSV文件 
  11.     */  
  12.     public void  readCsv(){  
  13.         try {      
  14.                 ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据   
  15.                 String csvFilePath = "D:/log/Alarm20101125.csv";  
  16.                 CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("SJIS"));    //一般用这编码读就可以了       
  17.                    
  18.                 reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。   
  19.                    
  20.                 while(reader.readRecord()){ //逐行读入除表头的数据       
  21.                     csvList.add(reader.getValues());  
  22.                 }              
  23.                 reader.close();  
  24.                    
  25.                 for(int row=0;row<csvList.size();row++){  
  26.                      String  cell = csvList.get(row)[0]; //取得第row行第0列的数据   
  27.                      System.out.println(cell);  
  28.                 }       
  29.             } catch (Exception ex) {  
  30.                     System.out.println(ex);  
  31.                 }  
  32.     }  
  33.       
  34.     /** 
  35.      * 写入CSV文件 
  36.      */  
  37.     public static void WriteCsv(){  
  38.         try {  
  39.                 String csvFilePath = "D:/log/Alarm20101125.csv";  
  40.                 CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));  
  41.                 String[] contents = {"告警信息","非法操作","没有权限","操作失败"};                      
  42.                 wr.writeRecord(contents);  
  43.                 wr.close();  
  44.          } catch (IOException e) {  
  45.             e.printStackTrace();  
  46.          }  
  47.     }  
  48. }  
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
 
public class DB2ExportCsv
{
    /**
    * 读取CSV文件
    */
    public void  readCsv(){
        try {    
				ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据
				String csvFilePath = "D:/log/Alarm20101125.csv";
				CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("SJIS"));    //一般用这编码读就可以了    
				 
				reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。
				 
				while(reader.readRecord()){ //逐行读入除表头的数据    
					csvList.add(reader.getValues());
				}            
				reader.close();
				 
				for(int row=0;row<csvList.size();row++){
				     String  cell = csvList.get(row)[0]; //取得第row行第0列的数据
				     System.out.println(cell);
				}     
			} catch (Exception ex) {
					System.out.println(ex);
				}
    }
    
    /**
     * 写入CSV文件
     */
    public static void WriteCsv(){
        try {
				String csvFilePath = "D:/log/Alarm20101125.csv";
				CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));
				String[] contents = {"告警信息","非法操作","没有权限","操作失败"};                    
				wr.writeRecord(contents);
				wr.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
    }
}

 想了解更多的函数请查看javacsv2.0/doc/index.html说明。我觉得javacsv2.0/src/AllTests.java看看也很有用。大家可以去试试

 

 

此代码可以解决字段中出现分隔符,双引号等等。。。


Java代码 复制代码  收藏代码
  1. /**  
  2.      * 对于文件中字段包含逗号的文件的特殊处理 (同时可以去除掉双引号)处理完以后会在相同的路径下输出相同文件名的TXT文件  
  3.      *   
  4.      * @throws Exception  
  5.      */  
  6.     public static void specialChar(String filePath,int starRow) throws Exception {   
  7.   
  8.         BufferedReader br = null;   
  9.         File f = new File(filePath);   
  10.         String fileName = f.getName();   
  11.   
  12.         if (!fileName.substring(fileName.indexOf(".") + 1).equals("csv")) {   
  13.             throw new Exception(filePath + "不是一个CSV文件");   
  14.         }   
  15.         File file = new File(StringUtil.replace(f.getPath(), "csv""txt"));   
  16.         FileWriter filewriter = null;   
  17.         try {   
  18.             br = new BufferedReader(new InputStreamReader(   
  19.                     new FileInputStream(f), "utf-8"));   
  20.             filewriter = new FileWriter(file, false);   
  21.             SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");   
  22.   
  23.             System.out.println(sd.format(new Date()));   
  24.             String tempString = null;   
  25.             int i = 0;   
  26.             while ((tempString = br.readLine()) != null) {   
  27.                 if (i < starRow-1) {   
  28.                     i++;   
  29.                     continue;   
  30.                 }   
  31.                 if(tempString.trim().equals(""))   
  32.                     break;   
  33.                 if (StringUtil.contains(tempString, "\"")) {   
  34.                     tempString = deepParser(tempString,filePath);   
  35.                 } else  
  36.                     tempString = StringUtil.replace(tempString, ",""|");   
  37. //              System.out.println(tempString);   
  38.                 filewriter.write(stringTrim(tempString, "\\|") + "\r\n");   
  39.                 i++;   
  40.             }   
  41.             System.out.println(sd.format(new Date()));   
  42.         } catch (Throwable e) {   
  43.             log.warn("解析文件:【" + filePath + "】出错", e);   
  44.             e.printStackTrace();   
  45.         } finally {   
  46.             try {   
  47.                 br.close();   
  48.                 filewriter.close();   
  49.             } catch (IOException e) {   
  50.                 e.printStackTrace();   
  51.             }   
  52.         }   
  53.   
  54.     }   
  55.   
  56.     public static String deepParser(String str,String filePath) {   
  57.         System.out.println(str);   
  58.         String temp = str;   
  59.                           str = str+",";   
  60.         StringBuffer sb = new StringBuffer();   
  61.         try {   
  62.             int from = 0;   
  63.             int end = str.length();   
  64.             int i = 0;   
  65.             while (StringUtil.contains((str = str.substring(from)), "\"")) {   
  66.                 from = str.indexOf("\"");   
  67.                 end = str.indexOf("\"", from + 1);   
  68.                 sb.append(StringUtil.replace(str.substring(0, from), ",""|"));   
  69.                 sb.append(str.substring(from + 1, end));   
  70.                 from = end + 1;   
  71.                 i++;   
  72.             }   
  73.             sb.append(StringUtil.replace(str, ",""|"));   
  74.         } catch (Throwable e) {   
  75.             log.warn("解析文件:【" + filePath + "】出错,一下数据有问题:"+temp, e);   
  76.             e.printStackTrace();   
  77.         }   
  78.                        String s = sb.toString();   
  79.              s = s.substring(0, s.lastIndexOf("|"));   
  80.              return s;   
  81.     }   
  82.   
  83.   
  84.     //去除字段2边空格,可以指定分隔符   
  85.     public static String stringTrim(String str, String regex) {   
  86.         str = str+" ";   
  87.         String[] strs = str.split(regex);   
  88.         StringBuffer sb = new StringBuffer();   
  89.   
  90.         for (int i = 0; i < strs.length; i++) {   
  91.             sb.append(strs[i].trim() + "|");   
  92.         }   
  93.   
  94.         return sb.toString().substring(0, sb.toString().lastIndexOf("|"));   
  95.     }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值