如果说 数据不是很多。 直接用编辑器(ue notepad等) 格式化后 输入到数据库。(注: 如果都是自己想要的数据 且有对应的格式与字段与数据库对应 ,可以直接导入到数据库)
数据很多的话 可以整理后导入数据库
也可也使用语言 读取文件,正则匹配出对应的内容。 之后整理成规则的sql 执行插入到数据库
package web;
import javaioBufferedReader;
import javaioFileReader;
import javasqlConnection;
import javasqlDriverManager;
import javasqlPreparedStatement;
import javautilArrayList;
import javautilList;
//插入的数据类
class Simple {
String date;
String size;
String number;
}
public class Client {
// 加载数据库驱动
static {
try {
ClassforName("commysqljdbcDriver");
} catch (ClassNotFoundException e) {
eprintStackTrace();
}
}
// 连结数据库
static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "123456";
Connection conn = null;
try {
conn = DriverManagergetConnection(url, user, password);
} catch (Exception e) {
eprintStackTrace();
}
return conn;
}
// 插入数据
static void insert(Simple simple) {
Connection conn = getConnection();
String sql = "INSERT INTO sample(date,size,number) VALUES(,,)";
PreparedStatement sm = null;
try {
sm = connprepareStatement(sql);
smsetString(1, simpledate);
smsetString(2, simplesize);
smsetString(3, simplenumber);
smexecute();
} catch (Exception e) {
eprintStackTrace();
}
}
// 获取文本内容列表
static List<Simple> getText(String filePath) {
List<Simple> simples = new ArrayList<Simple>();
try {
FileReader reader = new FileReader(filePath);
BufferedReader bfReader = new BufferedReader(reader);
String text = null;
while ((text = bfReaderreadLine()) != null) {
String[] texts = textsplit(" ");
Simple simple = new Simple();
simpledate = texts[0];
simplesize = texts[1];
simplenumber = texts[2];
simplesadd(simple);
}
} catch (Exception e) {
eprintStackTrace();
}
return simples;
}
public static void main(String[] args) {
// 获取文本内容
List<Simple> simples = getText("testtxt");
// 插入数据库
for (Simple simple : simples) {
insert(simple);
}
}
}
注:在Eclipse下,testtxt放在项目文件夹下,设置数据库驱动
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();
}
}
}
用IO读取文本文件,建议参看javaio包中FileInputStream类与InputStreamReader类的API文档。
用FileInputStream载入文件,
然后用InputStreamReader封装FileInputStream对象,
然后用InputStreamReader的read方法读取字符串,注意字符编码问题。
读取成字符串之后, *** 作字符串,先分行,得到不同网站的数据
再在行中分段,分别检出Name、url、status部分,
然后插入数据库即可
如果会的话,字符串 *** 作可以使用正则表达式。
不会的话,就用笨办法,循环套if else来检出所需要的数据。
主要就是IO *** 作与字符串 *** 作。
这个很简单啊 你以一行的形式读取 然后 拿到这行以后 判断这行的格式是否有日期 如果有的话 那麼就是 2009/12/7 否则就是 06:35 电视剧 家有儿女(第一部)
如果你要源码的话我可以现在给你写 有问题HI我 !!
//得到节目TXT
StreamReader sr = new StreamReader("D:\\jiangsutxt", EncodingGetEncoding("GBK"));
//读取到末尾
string txt = srReadToEnd();
//电视台
string dianshitai = stringEmpty;
//判断是否为空文本
if (!txtEquals(stringEmpty))
{
//分割文本
string[] oldString = txtReplace("\r\n", "@")Split('@');
//循环数组
foreach (string newTxt in oldString)
{
//是否日期
if (newTxtIndexOf("/") > 0)
{
//得到日期
}
//是否节目
else if (newTxtIndexOf(":"))
{
//得到节目
}
//电视台
else
{
//得到电视台
dianshitai = newTxt;
}
}
//再怎麼 *** 作数据库不用教了吧
以上就是关于提取txt文件中的内容写入到数据库里去全部的内容,包括:提取txt文件中的内容写入到数据库里去、使用java如何将txt文件读入数据库请各位大侠赐教、用java如何将txt文件导入mysql等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)