日期:2014-05-16  浏览次数:20422 次

java读取文本文件到mysql数据库【示例3】-批量导入文本文件

1、需求:批量导入文件夹“手机号码归属地”下的所有文本文件,如图:

2、java源代码:

package com.insigma.zd.group4.liuchao.jdbc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class ReadConfigureFile3 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "1234";
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
			stmt = conn.createStatement();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		File file = new File("D:\\share\\手机号码归属地");//得到所选择文件夹
		String path = file.getAbsolutePath();//得到选择文件夹的全路径
		String[] files = file.list();//取得文件夹下的所有文件
		try {
			conn.setAutoCommit(false);//设置数据手动提交,自己管理事务 
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//
		
		for(int i=0; i<files.length;i++){//遍历文件夹下所有文件
			String fileName = files[i].substring(0, files[i].lastIndexOf("."));//取得所选文件名
			String province = fileName.substring(0,fileName.length()-2);
			String cardType = fileName.substring(fileName.length()-2);
			FileInputStream fis = null;
			try {
				 fis = new FileInputStream(path+"\\"+files[i]);
				InputStreamReader input = new InputStreamReader(fis);
				BufferedReader br = new BufferedReader(input);
				String line = null;
				String sql = null;
				String info[] = null;
				
				try {
					while((line = br.readLine())!= null){
						info = line.split("-");
						sql = sql = "insert into telephone(startPhone,endPhone,city,province,cardType)values('"+ info[0] +"','"+info[1]+"','"+info[2]+"','"+province+"','"+cardType+"')";
						//stmt.executeUpdate(sql);
						stmt.addBatch(sql);
					}
					stmt.executeBatch();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				 
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				//提交事务
				conn.commit();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


 

 

3、成功导入到数据库: