用java如何将txt文件导入mysql

用java如何将txt文件导入mysql,第1张

Java中将txt文件导入到mysql基本的思路就是先使用I/O *** 作流获取到文件具体信息,然后将信息拼接成mysql插入到数据库中,示例如下:

1、先读取txt文件的内容,文件内容可以按照一定的规律进行排列,这样程序读取就方便。

import javaioIOException;

import javaioRandomAccessFile;

import javaioUnsupportedEncodingException;

import javatextSimpleDateFormat;

import javautilDate;

import javautilregexMatcher;

import javautilregexPattern;

import comconfigConstants;

import comutilsUUIDUtil;

/

txt文本数据 采集类

@see

/

public class UserDataGather {

public static final String TXT_FILE_PATH = "D://testUsertxt";

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 = rafreadLine();

while (line_record != null) {

// 解析每一条记录

parseRecord(line_record);

line_record = rafreadLine();

}

} catch (Exception e) {

eprintStackTrace();

}

}

/

功能:具体解析每一条记录,这里可以增加很多对记录的解析判断条件,如是否为字母、

/

@SuppressWarnings("static-access")

private void parseRecord(String line_record) throws Exception {

//拆分记录

// String[] fields = line_recordsplit(fieldLimitChar);

// Systemoutprintln(tranStr(line_record)+"Ok");

String temp = line_recordsubstring(line_recordindexOf(fieldLimitChar, 0), line_recordindexOf(" ", line_recordindexOf(fieldLimitChar, 0)));

// if (fieldslength == fieldAllCount) {

//

FltNum = tranStr(temp)trim()replace(fieldLimitChar,"")replace(" ","");

// Systemoutprintln(FltNum);

if(FltNumlength()>=4){

if(!isNumeric(FltNum)){

// Systemoutprintln(generateSql(FltNum)[0]toString());

// Systemoutprintln(generateSql(FltNum)[1]toString());

count++;

String[] temp1 = generateSql(FltNum);

MyFile mf = new MyFile();

mfcreatTxtFile("insertPinTuUserSql");

mfwriteTxtFile(temp1[0]toString());

mfcreatTxtFile("UUID");

mfwriteTxtFile(temp1[1]toString()+",");

}

}else if(FltNumlength() ==2 || FltNumlength() ==3){

if(!isNumeric(FltNum)){

if(!isTwoCharacter(FltNum)){

// Systemoutprintln(generateSql(FltNum)[0]toString());

// Systemoutprintln(generateSql(FltNum)[1]toString());

count++;

String[] temp2 = generateSql(FltNum);

MyFile mf = new MyFile();

mfcreatTxtFile("insertPinTuUserSql");

mfwriteTxtFile(temp2[0]toString());

mfcreatTxtFile("UUID");

mfwriteTxtFile(temp2[1]toString()+",");

}

}

}

// InsertDB db = new InsertDB();

//

// dbinsertDB(FltNum);

// }

}

@SuppressWarnings("static-access")

public String[] generateSql(String userName) throws IOException{

StringBuffer sbf = new StringBuffer();

String[] str = new String[2];

String uuid = UUIDUtilgetUUID();

sbfappend("insert into user values('"+uuid+"','" + userName +"','"+default_password+"',"+ConstantsENABLED+","+ConstantsNUllDELETE+","+ConstantsAUDITING+",'"+uuid+"@164com','"+formatDateTime()+"',"+ConstantsREGEDIT_USER+");/n");

sbfappend("insert into users values('"+uuid+"',"+ null+","+ConstantsMALE+","+null+","+null+",'6017636250','"+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");

sbfappend("insert into user_user_group values('"+uuid+"','"+ uuid +"','"+ConstantsPERSONAL_USER+"');/n");

UUID = uuid;

str[0]=sbftoString();

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");

Systemoutprintln(sdfformat(date));

return sdfformat(date);

}

private String tranStr(String oldstr) {

String newstr = "";

try {

newstr = new String(oldstrgetBytes("ISO-8859-1"), "utf-8");

} catch (UnsupportedEncodingException e) {

eprintStackTrace();

}

return newstr;

}

public static boolean isNumeric(String str){

Pattern pattern = Patterncompile("[0-9]");

return patternmatcher(str)matches();

}

public static boolean isTwoCharacter(String str){

String regEx="[a-zA-Z0-9]{2,3}";

Pattern p=Patterncompile(regEx);

Matcher m=pmatcher(str);

return mfind();

}

}

2、连接数据库执行数据导入

import javasqlDriverManager;

import javasqlResultSet;

import commysqljdbcConnection;

import commysqljdbcStatement;

/

插入数据库 生成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://192168106:3306/pintu";

private static final String driver = "commysqljdbcDriver";

public static Connection getCon() {

Connection con = null;

try {

ClassforName(driver)newInstance();

con = (Connection) DriverManagergetConnection(url, user, pwd);

if (con != null) {

Systemoutprintln("你已连接到数据库:" + congetCatalog());

}

} catch (Exception e) {

Systemoutprintln("连接数据库失败!");

eprintStackTrace();

}

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) concreateStatement();

int i = stmexecuteUpdate(sql);

if (i > 0) {

flag = true;

Systemoutprintln(flag + "插入数据成功!");

}

} catch (Exception e) {

flag = false;

eprintStackTrace();

} finally {

close(null, stm, con);

}

return flag;

}

//关闭相关连接

public void close(ResultSet rs, Statement stm, Connection con) {

if (rs != null)

try {

rsclose();

} catch (Exception e) {

eprintStackTrace();

}

if (stm != null)

try {

stmclose();

} catch (Exception e) {

eprintStackTrace();

}

if (con != null)

try {

conclose();

} catch (Exception e) {

eprintStackTrace();

}

}

}

存取就是二进制数据的存取问题

把以文件的时候读入到程序中

转换成byte

以byte显示保存到数据库中

另外,access保存文件~~不合适~

---------------------------

显示和存储没关系,看你要怎么显示了~显示到浏览器?

package comjspdevch13;

import comjspdevutil;

import javasql;

import javaxsql;

import javaio;

import oraclejdbcdriverOracleResultSet;

import oraclesqlBLOB;

public class BlobBean

{

Connection conn ;

/

构造方法,创建Connection对象,并且在数据库中添加一个表。

/

public BlobBean()throws Exception

{

DriverManagerregisterDriver(new oraclejdbcdriverOracleDriver());

conn = DriverManagergetConnection("jdbc:oracle:thin:system@127001:1521:hellking", "system", "manager");

// conncreateStatement()execute("create table blobtable(blobvalue blob)");

}

/

写入Blob数据到数据库

/

public void addBlob(String fileName)throws Exception

{

connsetAutoCommit(false);

Statement stmt = conncreateStatement();

stmtexecute("insert into blobtable values (empty_blob())");

ResultSet rset = stmtexecuteQuery("SELECT blobvalue FROM blobtable FOR UPDATE");

BLOB blob = null;

while (rsetnext()) {

blob = ((OracleResultSet) rset)getBLOB(1);

Systemoutprintln(bloblength());

}

File binaryFile = new File(fileName);

Systemoutprintln(fileName+"'s length = " + binaryFilelength());

FileInputStream instream = new FileInputStream(binaryFile);

OutputStream outstream = blobgetBinaryOutputStream();

int chunk = blobgetChunkSize();

Systemoutprintln("chunk size = " + chunk);

byte[] buffer = new byte[chunk];

int length = -1;

while ((length = instreamread(buffer)) != -1)

outstreamwrite(buffer, 0, length);

instreamclose();

outstreamclose();

conncommit();

}

这个是遍历java文件的,保存到数据库自己可以写吧

import javaioFile;

import javautilArrayList;

import javautilList;

public class $ {

public static void main(String _) {

String path = "D:/";

List data = new ArrayList();

data = getData(path, data);

for (int i = 0; i < datasize(); i++) {

Systemoutprintln(dataget(i));

}

}

private static List getData(String path, List data) {

File f = new File(path);

// 是文件夹

if (fisDirectory()) {

File[] fs = flistFiles();

for (int i = 0; i < fslength; i++) {

data = getData(fs[i]getPath(), data);

}

} else if (fgetName()endsWith("java")) {

dataadd(fgetName());

}

return data;

}

}

1、java i/o读取txt文本

2、使用实体类封装或使用list、map等封装读取到的数据

3、jdbc

txt文本要保证符合一定的格式,如每个字段间已特定字符分割。

直接读写文件,再把读出来的文件内容格式化成json,再用JDBC、Mybatis或者其他框架将json数据存入数据库。

假设实体类是这样的:

public class ElectSet {

public String xueqi;

public String xuenian;

public String startTime;

public String endTime;

public int menshu;

public String isReadDB;

//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}

public String getXueqi() {

   return xueqi;

}

public void setXueqi(String xueqi) {

   thisxueqi = xueqi;

}

public String getXuenian() {

   return xuenian;

}

public void setXuenian(String xuenian) {

   thisxuenian = xuenian;

}

public String getStartTime() {

   return startTime;

}

public void setStartTime(String startTime) {

   thisstartTime = startTime;

}

public String getEndTime() {

   return endTime;

}

public void setEndTime(String endTime) {

   thisendTime = endTime;

}

public int getMenshu() {

   return menshu;

}

public void setMenshu(int menshu) {

   thismenshu = menshu;

}

public String getIsReadDB() {

   return isReadDB;

}

public void setIsReadDB(String isReadDB) {

   thisisReadDB = isReadDB;

}

}

有一个json格式的文件,存的信息如下:

Setsjson:

{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}

具体 *** 作:

/

 取出文件内容,填充对象

/

public ElectSet findElectSet(String path){

   ElectSet electset=new ElectSet();

   String sets=ReadFile(path);//获得json文件的内容

   JSONObject jo=JSONObjectfromObject(sets);//格式化成json对象

   //Systemoutprintln("------------" jo);

   //String name = jogetString("xuenian");

   //Systemoutprintln(name);

   electsetsetXueqi(jogetString("xueqi"));

   electsetsetXuenian(jogetString("xuenian"));

   electsetsetStartTime(jogetString("startTime"));

   electsetsetEndTime(jogetString("endTime"));

   electsetsetMenshu(jogetInt("menshu"));

   electsetsetIsReadDB(jogetString("isReadDB"));

   return electset;

}

//设置属性,并保存

public boolean setElect(String path,String sets){

   try {

    writeFile(path,sets);

    return true;

   } catch (IOException e) {

    // TODO Auto-generated catch block

    eprintStackTrace();

    return false;

   }

}

//读文件,返回字符串

public String ReadFile(String path){

    File file = new File(path);

    BufferedReader reader = null;

    String laststr = "";

    try {

     //Systemoutprintln("以行为单位读取文件内容,一次读一整行:");

     reader = new BufferedReader(new FileReader(file));

     String tempString = null;

     int line = 1;

     //一次读入一行,直到读入null为文件结束

     while ((tempString = readerreadLine()) != null) {

      //显示行号

      Systemoutprintln("line " line ": " tempString);

      laststr = laststr tempString;

      line ;

     }

     readerclose();

    } catch (IOException e) {

     eprintStackTrace();

    } finally {

     if (reader != null) {

      try {

       readerclose();

      } catch (IOException e1) {

      }

     }

    }

    return laststr;

}

将获取到的字符串,入库即可。

java ssm文件上传后怎么写入数据库表中:

主要在上传文件完成后,通过mybatis ORM框架进行数据库表字段URL文件路径的写入;

这边主要是看你写到那个字段,先定义好,再执行上传文件,文件上传成功后,只需要存入上传文件URL(文件路径)/文件名都可以,这块比较灵活,关键看你自己怎么保存;

以上就是关于用java如何将txt文件导入mysql全部的内容,包括:用java如何将txt文件导入mysql、在java中如何将图片保存到数据库、JAVA语言写文件存取,存到ORACLE数据库里怎么写等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9440867.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存