用java如何将txt文件导入mysql
想设计个页面先导入txt文件,然后点击查询,将txt文件的内容按照格式查询出来,然后将内容插入到数据库里面。具体应该怎么做呢?...
想设计个页面先导入txt文件,然后点击查询,将txt文件的内容按照格式查询出来,然后将内容插入到数据库里面。具体应该怎么做呢?
展开
5个回答
展开全部
Java中将txt文件导入到mysql基本的思路就是先使用I/O操作流获取到文件具体信息,然后将信息拼接成mysql插入到数据库中,示例如下:
1、先读取txt文件的内容,文件内容可以按照一定的规律进行排列,这样程序读取就方便。
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.config.Constants;
import com.utils.UUIDUtil;
/**
* txt文本数据 采集类
*
* @see
*/
public class UserDataGather {
public static final String TXT_FILE_PATH = "D://testUser.txt";
public static final String openFileStyle = "r";
public static final String fieldLimitChar = ".";
public static final int fieldAllCount = 1;
public static final String default_password = "PTMD0309";
public Integer count = 0;
private String FltNum;
public String UUID;
/**
* 功能:解析文本文件
*/
public void loadFile() {
try {
RandomAccessFile raf = new RandomAccessFile(TXT_FILE_PATH, openFileStyle);
String line_record = raf.readLine();
while (line_record != null) {
// 解析每一条记录
parseRecord(line_record);
line_record = raf.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 功能:具体解析每一条记录,这里可以增加很多对记录的解析判断条件,如是否为字母、
*/
@SuppressWarnings("static-access")
private void parseRecord(String line_record) throws Exception {
//拆分记录
// String[] fields = line_record.split(fieldLimitChar);
// System.out.println(tranStr(line_record)+"Ok");
String temp = line_record.substring(line_record.indexOf(fieldLimitChar, 0), line_record.indexOf(" ", line_record.indexOf(fieldLimitChar, 0)));
// if (fields.length == fieldAllCount) {
//
FltNum = tranStr(temp).trim().replace(fieldLimitChar,"").replace(" ","");
// System.out.println(FltNum);
if(FltNum.length()>=4){
if(!isNumeric(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp1 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp1[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp1[1].toString()+",");
}
}else if(FltNum.length() ==2 || FltNum.length() ==3){
if(!isNumeric(FltNum)){
if(!isTwoCharacter(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp2 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp2[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp2[1].toString()+",");
}
}
}
// InsertDB db = new InsertDB();
//
// db.insertDB(FltNum);
// }
}
@SuppressWarnings("static-access")
public String[] generateSql(String userName) throws IOException{
StringBuffer sbf = new StringBuffer();
String[] str = new String[2];
String uuid = UUIDUtil.getUUID();
sbf.append("insert into user values('"+uuid+"','" + userName +"','"+default_password+"',"+Constants.ENABLED+","+Constants.NUllDELETE+","+Constants.AUDITING+",'"+uuid+"@164.com','"+formatDateTime()+"',"+Constants.REGEDIT_USER+");/n");
sbf.append("insert into users values('"+uuid+"',"+ null+","+Constants.MALE+","+null+","+null+",'60.176.36.250','"+formatDateTime()+"',"+null+","+null+","+null+","+null+","+null+","+null+",0,"+null+","+null+",0,0,0,'"+formatDateTime()+"','1036',0,"+null+","+null+","+null+","+null+","+null+",'11',"+null+","+null+","+null+","+null+","+null+");/n");
sbf.append("insert into user_user_group values('"+uuid+"','"+ uuid +"','"+Constants.PERSONAL_USER+"');/n");
UUID = uuid;
str[0]=sbf.toString();
str[1]=UUID;
return str;
}
public String formatDateTime(){
Date date = new Date();
/**
* 时间格式化2009-12-31 09:04:31
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
return sdf.format(date);
}
private String tranStr(String oldstr) {
String newstr = "";
try {
newstr = new String(oldstr.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newstr;
}
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isTwoCharacter(String str){
String regEx="[a-zA-Z0-9]{2,3}";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(str);
return m.find();
}
}
2、连接数据库执行数据导入
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* 插入数据库 生成sql语句
*
* created on Mar 8, 2010
* @see
*/
public class InsertDB {
private static final String user = "pintu";
private static final String pwd = "pintu";
private static final String url = "jdbc:mysql://192.168.10.6:3306/pintu";
private static final String driver = "com.mysql.jdbc.Driver";
public static Connection getCon() {
Connection con = null;
try {
Class.forName(driver).newInstance();
con = (Connection) DriverManager.getConnection(url, user, pwd);
if (con != null) {
System.out.println("你已连接到数据库:" + con.getCatalog());
}
} catch (Exception e) {
System.out.println("连接数据库失败!");
e.printStackTrace();
}
return con;
}
public boolean insertDB(String FltNum) {
Connection con = null;
Statement stm = null;
boolean flag = false;
String sql = "insert into t_FltPsgInfo values('" + FltNum +
// "','"
// + FltLine + "','" + FltDate + "','" + PsgName + "','" + PsgType
//
// + "','" + PsgSex + "','" + PsgCab + "','" + PsgSeatNo + "','"
//
// + PsgInfo +
"')";
try {
con = getCon();
stm = (Statement) con.createStatement();
int i = stm.executeUpdate(sql);
if (i > 0) {
flag = true;
System.out.println(flag + "插入数据成功!");
}
} catch (Exception e) {
flag = false;
e.printStackTrace();
} finally {
close(null, stm, con);
}
return flag;
}
//关闭相关连接
public void close(ResultSet rs, Statement stm, Connection con) {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
if (stm != null)
try {
stm.close();
} catch (Exception e) {
e.printStackTrace();
}
if (con != null)
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1、先读取txt文件的内容,文件内容可以按照一定的规律进行排列,这样程序读取就方便。
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.config.Constants;
import com.utils.UUIDUtil;
/**
* txt文本数据 采集类
*
* @see
*/
public class UserDataGather {
public static final String TXT_FILE_PATH = "D://testUser.txt";
public static final String openFileStyle = "r";
public static final String fieldLimitChar = ".";
public static final int fieldAllCount = 1;
public static final String default_password = "PTMD0309";
public Integer count = 0;
private String FltNum;
public String UUID;
/**
* 功能:解析文本文件
*/
public void loadFile() {
try {
RandomAccessFile raf = new RandomAccessFile(TXT_FILE_PATH, openFileStyle);
String line_record = raf.readLine();
while (line_record != null) {
// 解析每一条记录
parseRecord(line_record);
line_record = raf.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 功能:具体解析每一条记录,这里可以增加很多对记录的解析判断条件,如是否为字母、
*/
@SuppressWarnings("static-access")
private void parseRecord(String line_record) throws Exception {
//拆分记录
// String[] fields = line_record.split(fieldLimitChar);
// System.out.println(tranStr(line_record)+"Ok");
String temp = line_record.substring(line_record.indexOf(fieldLimitChar, 0), line_record.indexOf(" ", line_record.indexOf(fieldLimitChar, 0)));
// if (fields.length == fieldAllCount) {
//
FltNum = tranStr(temp).trim().replace(fieldLimitChar,"").replace(" ","");
// System.out.println(FltNum);
if(FltNum.length()>=4){
if(!isNumeric(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp1 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp1[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp1[1].toString()+",");
}
}else if(FltNum.length() ==2 || FltNum.length() ==3){
if(!isNumeric(FltNum)){
if(!isTwoCharacter(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp2 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp2[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp2[1].toString()+",");
}
}
}
// InsertDB db = new InsertDB();
//
// db.insertDB(FltNum);
// }
}
@SuppressWarnings("static-access")
public String[] generateSql(String userName) throws IOException{
StringBuffer sbf = new StringBuffer();
String[] str = new String[2];
String uuid = UUIDUtil.getUUID();
sbf.append("insert into user values('"+uuid+"','" + userName +"','"+default_password+"',"+Constants.ENABLED+","+Constants.NUllDELETE+","+Constants.AUDITING+",'"+uuid+"@164.com','"+formatDateTime()+"',"+Constants.REGEDIT_USER+");/n");
sbf.append("insert into users values('"+uuid+"',"+ null+","+Constants.MALE+","+null+","+null+",'60.176.36.250','"+formatDateTime()+"',"+null+","+null+","+null+","+null+","+null+","+null+",0,"+null+","+null+",0,0,0,'"+formatDateTime()+"','1036',0,"+null+","+null+","+null+","+null+","+null+",'11',"+null+","+null+","+null+","+null+","+null+");/n");
sbf.append("insert into user_user_group values('"+uuid+"','"+ uuid +"','"+Constants.PERSONAL_USER+"');/n");
UUID = uuid;
str[0]=sbf.toString();
str[1]=UUID;
return str;
}
public String formatDateTime(){
Date date = new Date();
/**
* 时间格式化2009-12-31 09:04:31
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
return sdf.format(date);
}
private String tranStr(String oldstr) {
String newstr = "";
try {
newstr = new String(oldstr.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newstr;
}
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isTwoCharacter(String str){
String regEx="[a-zA-Z0-9]{2,3}";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(str);
return m.find();
}
}
2、连接数据库执行数据导入
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* 插入数据库 生成sql语句
*
* created on Mar 8, 2010
* @see
*/
public class InsertDB {
private static final String user = "pintu";
private static final String pwd = "pintu";
private static final String url = "jdbc:mysql://192.168.10.6:3306/pintu";
private static final String driver = "com.mysql.jdbc.Driver";
public static Connection getCon() {
Connection con = null;
try {
Class.forName(driver).newInstance();
con = (Connection) DriverManager.getConnection(url, user, pwd);
if (con != null) {
System.out.println("你已连接到数据库:" + con.getCatalog());
}
} catch (Exception e) {
System.out.println("连接数据库失败!");
e.printStackTrace();
}
return con;
}
public boolean insertDB(String FltNum) {
Connection con = null;
Statement stm = null;
boolean flag = false;
String sql = "insert into t_FltPsgInfo values('" + FltNum +
// "','"
// + FltLine + "','" + FltDate + "','" + PsgName + "','" + PsgType
//
// + "','" + PsgSex + "','" + PsgCab + "','" + PsgSeatNo + "','"
//
// + PsgInfo +
"')";
try {
con = getCon();
stm = (Statement) con.createStatement();
int i = stm.executeUpdate(sql);
if (i > 0) {
flag = true;
System.out.println(flag + "插入数据成功!");
}
} catch (Exception e) {
flag = false;
e.printStackTrace();
} finally {
close(null, stm, con);
}
return flag;
}
//关闭相关连接
public void close(ResultSet rs, Statement stm, Connection con) {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
if (stm != null)
try {
stm.close();
} catch (Exception e) {
e.printStackTrace();
}
if (con != null)
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2013-12-10
展开全部
if(arg0.getActionCommand().equals("open"))
{
如果是从数据库读取,代码如下
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("请选择文件...");
jfc.showOpenDialog(null);
jfc.setVisible(true);
String filename=jfc.getSelectedFile().getAbsolutePath();//文件路径
System.out.println(filename);
FileReader fr=null;
BufferedReader br=null;
try{
//读入文件
fr=new FileReader(filename);
br=new BufferedReader(fr);
String s;
String all=null;
//循环读取
while((s=br.readLine())!=null)
{
all+=s+"\r\n";
//System.out.println(s);
}
jta.setText(all);
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try{
br.close();
fr.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
else if(arg0.getActionCommand().equals("save"))
{
//如果是添加完再保存,代码如下
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("保存");
jfc.setVisible(true);
jfc.showSaveDialog(null);
String filename=jfc.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
BufferedWriter bw=null;
try{
fw=new FileWriter(filename);
bw=new BufferedWriter(fw);;
bw.write(this.jta.getText());
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try{
bw.close();
fw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
{
如果是从数据库读取,代码如下
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("请选择文件...");
jfc.showOpenDialog(null);
jfc.setVisible(true);
String filename=jfc.getSelectedFile().getAbsolutePath();//文件路径
System.out.println(filename);
FileReader fr=null;
BufferedReader br=null;
try{
//读入文件
fr=new FileReader(filename);
br=new BufferedReader(fr);
String s;
String all=null;
//循环读取
while((s=br.readLine())!=null)
{
all+=s+"\r\n";
//System.out.println(s);
}
jta.setText(all);
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try{
br.close();
fr.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
else if(arg0.getActionCommand().equals("save"))
{
//如果是添加完再保存,代码如下
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("保存");
jfc.setVisible(true);
jfc.showSaveDialog(null);
String filename=jfc.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
BufferedWriter bw=null;
try{
fw=new FileWriter(filename);
bw=new BufferedWriter(fw);;
bw.write(this.jta.getText());
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try{
bw.close();
fw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
输入输出流可以读取txt文件,可以将txt存入数据库,不过关于文件的存储,还是保存到磁盘上比较好。读取快捷方便,只用保存路径即可,
追问
还是有点不太明白。可以再具体点么?
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
页面导入txt文件 点击查询的时候调用 使用流解析txt文件获取内容并且将内容插入数据库的方法
这个很简单的 从网上搜索 java解析txt文件导入数据库 就行。
这个很简单的 从网上搜索 java解析txt文件导入数据库 就行。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
下载个 navicat8_mysql_cs 工具 就可以导入
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询