java读取scv文件_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java读取scv文件

java读取scv文件

 2015/4/15 21:46:22  羊小绵  程序员俱乐部  我要评论(0)
  • 摘要:CSV其实就是COMMASEPARATEDVALUE的缩写。在开发中用Java操作csv文件有专门的的API叫javacsv.jarjavacsv.jar下载地址:http://sourceforge.net/project/showfiles.php?group_id=33066下面演示一段操作代码仅供参考:Java代码packagecom.syc.test.bean;publicclassReslutBean{Stringhelp_keyword_id;Stringname
  • 标签:文件 Java
CSV其实就是COMMA SEPARATED VALUE的缩写。
在开发中用Java操作csv文件有专门的的API叫javacsv.jar

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

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

Java代码
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] view plaincopy
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代码
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 JavaCSV {  
    /** 
     * @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代码
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代码
/** 
     * 对于文件中字段包含逗号的文件的特殊处理 (同时可以去除掉双引号)处理完以后会在相同的路径下输出相同文件名的TXT文件 
     *  
     * @throws Exception 
     */ 
    public static void specialChar(String filePath,int starRow) throws Exception {  
 
        BufferedReader br = null;  
        File f = new File(filePath);  
        String fileName = f.getName();  
 
        if (!fileName.substring(fileName.indexOf(".") + 1).equals("csv")) {  
            throw new Exception(filePath + "不是一个CSV文件");  
        }  
        File file = new File(StringUtil.replace(f.getPath(), "csv", "txt"));  
        FileWriter filewriter = null;  
        try {  
            br = new BufferedReader(new InputStreamReader(  
                    new FileInputStream(f), "utf-8"));  
            filewriter = new FileWriter(file, false);  
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
 
            System.out.println(sd.format(new Date()));  
            String tempString = null;  
            int i = 0;  
            while ((tempString = br.readLine()) != null) {  
                if (i < starRow-1) {  
                    i++;  
                    continue;  
                }  
                if(tempString.trim().equals(""))  
                    break;  
                if (StringUtil.contains(tempString, "\"")) {  
                    tempString = deepParser(tempString,filePath);  
                } else 
                    tempString = StringUtil.replace(tempString, ",", "|");  
//              System.out.println(tempString);  
                filewriter.write(stringTrim(tempString, "\\|") + "\r\n");  
                i++;  
            }  
            System.out.println(sd.format(new Date()));  
        } catch (Throwable e) {  
            log.warn("解析文件:【" + filePath + "】出错", e);  
            e.printStackTrace();  
        } finally {  
            try {  
                br.close();  
                filewriter.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
 
    }  
 
    public static String deepParser(String str,String filePath) {  
        System.out.println(str);  
        String temp = str;  
                          str = str+",";  
        StringBuffer sb = new StringBuffer();  
        try {  
            int from = 0;  
            int end = str.length();  
            int i = 0;  
            while (StringUtil.contains((str = str.substring(from)), "\"")) {  
                from = str.indexOf("\"");  
                end = str.indexOf("\"", from + 1);  
                sb.append(StringUtil.replace(str.substring(0, from), ",", "|"));  
                sb.append(str.substring(from + 1, end));  
                from = end + 1;  
                i++;  
            }  
            sb.append(StringUtil.replace(str, ",", "|"));  
        } catch (Throwable e) {  
            log.warn("解析文件:【" + filePath + "】出错,一下数据有问题:"+temp, e);  
            e.printStackTrace();  
        }  
                       String s = sb.toString();  
             s = s.substring(0, s.lastIndexOf("|"));  
             return s;  
    }  
 
 
    //去除字段2边空格,可以指定分隔符  
    public static String stringTrim(String str, String regex) {  
        str = str+" ";  
        String[] strs = str.split(regex);  
        StringBuffer sb = new StringBuffer();  
 
        for (int i = 0; i < strs.length; i++) {  
            sb.append(strs[i].trim() + "|");  
        }  
 
        return sb.toString().substring(0, sb.toString().lastIndexOf("|"));  
    }
上一篇: 如何在Linux下递归查看所有文件或目录? 下一篇: 没有下一篇了!
发表评论
用户名: 匿名