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;
Read using the Fileutils class of the Commons-io.jar package
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 ();
Row Data Conversion Array
string[] Custarray = Line.split ("\\|");
Insertcustinfo (Custarray);
Thread.Sleep (10);
}
} catch (IOException e) {
E.printstacktrace ();
} catch (Interruptedexception e) {
E.printstacktrace ();
} finally {
Dbdisconnection ();
}
}
inserting into the database
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.executeupdate ();
} catch (SQLException e) {
E.printstacktrace ();
} finally {
if (pstmt! = null) {
try {
Pstmt.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
}
}
Connecting to a 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 Open! ");
} catch (ClassNotFoundException e) {
E.printstacktrace ();
} catch (SQLException e) {
E.printstacktrace ();
}
Return conn;
}
Close the database
public void Dbdisconnection () {
IF (conn! = null) {
try {
Conn.close ();
System.out.println ("Connection off! ");
} catch (SQLException e) {
E.printstacktrace ();
}
}
}
public static void Main (string[] args) {
Readcustomerfile RCF = new Readcustomerfile ();
Rcf.readtxtfilebyfileutils ("D:\\test\\customer_info.txt");
}
}
Java read TXT file, read results saved to database