java实现把csv文件导入到sqlserver

Python012

java实现把csv文件导入到sqlserver,第1张

可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。 BufferedReader bre = nulltry {String file = "D:/test/test.txt"bre = new BufferedReader(new FileReader(file))//此时获取到的bre就是整个文件的缓存流while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环{ String item[] = bre.split(",")//CSV格式文件为逗号分隔符文件,这里根据逗号切分 String last = item[item.length-1]//通过此方法获取到数据信息//int value = Integer.parseInt(last)//如果是数值,可以转化为数值 System.out.println(last)//此处转换成数据库相应的语句即可实现存储操作};备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。

所以你写csv表格,这么做就可以了,每写一列就加一个,就是第二列。

距离有个BufferWriter writer对象要写一个csv文件。

writer.wrtie("第一列");

writer.write(",")

writer.write("第二列")

这就是一个简单的用,分割的csv文件。

package cn.com.sunjapan.university.web

import java.util.ArrayList

import java.util.Vector

import org.apache.commons.logging.Log

import org.apache.commons.logging.LogFactory

import cn.com.sunjapan.comlib.exception.PJException

import cn.com.sunjapan.framework.core.misc.ChainedException

public class ParseCsvUtil {

transient private static Log log = LogFactory.getLog(ParseCsvUtil.class)

/** 屏蔽构造函数 */

    private ParseCsvUtil() {

    }

    /** 单子模式静态变量 */

    private static ParseCsvUtil instance

    /**

     * 获取静态方法

     * 

     * @return 静态变量

     */

    public static synchronized ParseCsvUtil getInstance() {

        if (instance == null) {

            instance = new ParseCsvUtil()

        }

        return instance

    }

    /**

     * 得到文件头的数据<br>

     * 

     * @param csvdata

     *            头文件信息

     * @return 头文件信息

     */

    public ArrayList<String> parseCsvHeadData(String[][] csvdata) {

        if (log.isDebugEnabled()) {

            log.debug("now we enter parseCsvHeadData of ParseCsvFileManager")

        }

        ArrayList<String> csvHeadList = new ArrayList<String>()

        for (int i = 0 i < csvdata[0].length i++) {

            csvHeadList.add(csvdata[0][i])

        }

        return csvHeadList

    }

    /**

     * 得到文件内容的list<br>

     * 

     * @param csvdata

     *            文件内容

     * @return 文件内容

     */

    public ArrayList<String[]> parseCsvData(String[][] csvdata) {

        if (log.isDebugEnabled()) {

            log.debug("now we enter parseCsvData of ParseCsvFileManager")

        }

        ArrayList<String[]> csvList = new ArrayList<String[]>()

        for (int i = 1 i < csvdata.length i++) {

            csvList.add(csvdata[i])

        }

        return csvList

    }

    

    /**

     * 解析csv文件一行数据

     * 

     * @param csvLine

     *            csv文件的一行数据

     * @return 解析后的字符串数组

     * @throws ChainedException

     *             抛出异常

     */

    public static String[] parseCsvLine(String csvLine) throws ChainedException {

        if (log.isDebugEnabled()) {

            log.debug("now we enter parseCsvLine of CSVFileParse")

        }

        String[] retArray = null

        if (csvLine == null || csvLine.trim().length() <= 0) {

            return null

        }

        StringBuffer sbuf = new StringBuffer()

        Vector<String> result = new Vector<String>()

        boolean beginWithQuote = false

        int length = csvLine.length()

        for (int i = 0 i < length i++) {

            char ch = csvLine.charAt(i)

            if (ch == '\"') {

                if (beginWithQuote) {

                    i++

                    if (i >= length) {

                        result.addElement(sbuf.toString())

                        sbuf = new StringBuffer()

                        beginWithQuote = false

                    } else {

                        ch = csvLine.charAt(i)

                        if (ch == '\"') {

                            sbuf.append(ch)

                        } else if (ch == ',') {

                            result.addElement(sbuf.toString())

                            sbuf = new StringBuffer()

                            beginWithQuote = false

                        } else {

                            throw new ChainedException(

                                    "Single double-quote char mustn't exist in filed "

                                            + (result.size() + 1)

                                            + " while it is begined with quote\nchar at:"

                                            + i)

                        }

                    }

                } else if (sbuf.length() == 0) {

                    beginWithQuote = true

                } else {

                    throw new ChainedException(

                            "Quote cannot exist in a filed which doesn't begin with quote!\nfield:"

                                    + (result.size() + 1))

                }

            } else if (ch == ',') {

                if (beginWithQuote) {

                    sbuf.append(ch)

                } else {

                    result.addElement(sbuf.toString())

                    sbuf = new StringBuffer()

                    beginWithQuote = false

                }

            } else {

                sbuf.append(ch)

            }

        }

        if (sbuf.length() != 0) {

            if (beginWithQuote) {

                throw new ChainedException(

                        "last field is begin with but not end with double quote")

            } else {

                result.addElement(sbuf.toString())

            }

        }

        retArray = new String[result.size()]

        for (int i = 0 i < retArray.length i++) {

            retArray[i] = (String) result.elementAt(i)

        }

        return retArray

    }

    

    /**

     * 导出文件<br>

     * 

     * @param request

     *            HttpServletRequest

     * @return 导出文件

     * @throws ChainedException

     *             ChainedException

     */

    public ArrayList<String[]>  outFileList(String[][] content)

            throws ChainedException {

        if (log.isDebugEnabled()) {

            log.debug("now we enter outFileList of ParseCsvFileManager")

        }

        ArrayList<String[]>  list = new ArrayList<String[]> ()

        try {

            if (content.length > 0) {

                for (int i = 0 i < content.length i++) {

                 String lineValue = ""

                 for(int x = 0 x < content[i].length x++){

                 if(x == content[i].length - 1){

                 lineValue += content[i][x]

                 }else {

                 lineValue += content[i][x] + ","

                 }

                 }

                 // 解析字符串把null替换成空的

                 String[] valueList = parseCsvLine(lineValue

                 .replaceAll("null", "")

                 + ",")

                 list.add(valueList)

                }

            }

        } catch (PJException e) {

            // TODO 自动生成 catch 块

            e.printStackTrace()

        }

        return list

    }

}