Java reads txt files and saves the read results to the database. javatxt
Requirement: there is a large txt file (1,000,000 pieces of data) that reads useful databases from the txt file and saves them to the Oracle database.
Java implementation:
1. Read one row after the file is loaded
2. Insert data to the database by row after database connection
Package com. test. IF. service; import java. io. file; import java. io. IOException; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. SQLException; import org. apache. commons. io. fileUtils; import org. apache. commons. io. lineIterator; public class ReadCustomerFile {int idx; Connection conn = null; PreparedStatement pstmt = null; // use the FileUti of the commons-io.jar package Ls class reads public void readTxtFileByFileUtils (String fileName) {File file = new File (fileName); dbConnection (); try {LineIterator lineIterator = FileUtils. lineIterator (file, "GB2312"); while (lineIterator. hasNext () {String line = lineIterator. nextLine (); // convert the row data to an array String [] custArray = line. split ("\ |"); insertCustInfo (custArray); Thread. sleep (10) ;}} catch (IOException e) {e. printStackTrace ();} Catch (InterruptedException e) {e. printStackTrace () ;}finally {dbDisConnection () ;}// insert public void insertCustInfo (String [] strArray) {try {StringBuffer sqlBf = new StringBuffer (); sqlBf. setLength (0); sqlBf. append ("insert into TEMP_CUST_INFO (CUST_NO, CUST_NM, MOB_NO1) \ n"); sqlBf. append ("VALUES (? \ N "); sqlBf. append (",? \ N "); sqlBf. append (",?) \ N "); pstmt = conn. prepareStatement (sqlBf. toString (); idx = 1; pstmt. clearParameters (); pstmt. setInt (idx ++, Integer. parseInt (strArray [0]); pstmt. setString (idx ++, strArray [1]); pstmt. setString (idx ++, strArray [2]); pstmt.exe cuteUpdate ();} catch (SQLException e) {e. printStackTrace ();} finally {if (pstmt! = Null) {try {pstmt. close ();} catch (SQLException e) {e. printStackTrace () ;}}}// Connection database public Connection dbConnection () {try {Class. forName ("oracle. jdbc. driver. oracleDriver "); String url =" jdbc: oracle: thin: @ 127.0.0.1: 1521: orcl "; String user =" scott "; String password =" goodluck "; conn = DriverManager. getConnection (url, user, password); System. out. println ("Connection enabled! ");} Catch (ClassNotFoundException e) {e. printStackTrace ();} catch (SQLException e) {e. printStackTrace () ;}return conn ;}// close the public void dbDisConnection () {if (conn! = Null) {try {conn. close (); System. out. println ("Connection closed! ");} Catch (SQLException e) {e. printStackTrace () ;}} public static void main (String [] args) {ReadCustomerFile rcf = new ReadCustomerFile (); rcf. readTxtFileByFileUtils ("D :\\ test \ customer_info.txt ");}}
Confirm database data: