文本文件内容如下 存于E:\test\testforjava下的 testforjava.txt中
1 whp
2 hpw
3 pwh
4 wph
5 hwp
6 phw
创建java桌面应用程序 选择数据库应用程序
java读取该文本文件:源码如下
/*
* DesktopApplication1.java
*/
package desktopapplication1;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DesktopApplication1 extends SingleFrameApplication {
@Override protected void startup() {
show(new DesktopApplication1View(this));
}
@Override protected void configureWindow(java.awt.Window root) {
}
public static DesktopApplication1 getApplication() {
return Application.getInstance(DesktopApplication1.class);
}
public static void main(String[] args) {
launch(DesktopApplication1.class, args);
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testforjava"; //数据库地址
String username = "root";
String password = "root";
Connection conn = null;
Statement stmt = null;
File file = new File("E:\\test\\testforjava\\testforjava.txt"); //读取目录文件下的txt文件
StringBuffer sql = null;
BufferedReader reader = null;
String line = null;
String[] str = null;
String beginNumber = null;
String endNumber = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
reader = new BufferedReader(new FileReader(file));
stmt = conn.createStatement();
while((line = reader.readLine())!= null){
sql = new StringBuffer();
str = line.split(" ");//这边如果两个数据间用-隔开,那就在""之间填写-比如 str = line.split("_");
beginNumber = str[0];
endNumber = str[1];
sql.append("insert into whp(id,name) values('"); //这里就是sql语句了,表名和元素名 注意对应
sql.append(beginNumber+"','");
sql.append(endNumber+"')");
stmt.executeUpdate(sql.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行一下,就行了
===================================
对于导入时出现中文乱码,首先发现不是数据库mysql的问题,因为查询数据库编码时发现我们安装数据库时已经进行了字符集设置
所以就看了一下netbeans的设置,发现从txt拿出来时就已经乱码了,所以应该是netbeans的问题。
进行项目属性,更改netbeans的字符集
就好了