如何在 Java 中使用线程实现此文本文件读/写程序?



我有一个包含 1300000 行的文本文件。在java类中,我有一个名为textloadutility((的方法,它是从jsp页面调用的。有人可以提供这个 java 程序的异步线程实现吗?

package Snomed;
import catalog.Root;
import java.io.*;
import java.sql.PreparedStatement;
import org.json.JSONObject;
public class Textfileimport {

public String textloadutility() throws Exception {
Root oRoot = null;
PreparedStatement oPrStmt = null;
FileReader in = null;
BufferedReader br=null;
final int batchSize = 1000;
int count = 0;
JSONObject oJson = null;

String str=null;
oJson = new JSONObject();
oJson.put("status","failure");
str=oJson.toString();

try {

oRoot = Root.createDbConnection(null);


String sql = "INSERT INTO textfiledata (col1,col2,col3,col4,col5,col6,col7,col8,col9) VALUES( ?, ?, ?,?,?,?,?,?,?)";
oPrStmt = oRoot.con.prepareStatement(sql);
in = new FileReader("C:/Users/i2cdev001/Desktop/snomedinfo_data.txt");      
br = new BufferedReader(in);
String strLine;
while ((strLine = br.readLine()) != null){
String [] splitSt =strLine.split("\t");
String dat1="",dat2="",dat3="",dat4="",dat5="",dat6="",dat7="",dat8="",dat9="";
dat1=splitSt[0];
dat2=splitSt[1];
dat3=splitSt[2];
dat4=splitSt[3];
dat5=splitSt[4];
dat6=splitSt[5];
dat7=splitSt[6];
dat8=splitSt[7];
dat9=splitSt[8];        


oPrStmt.setString(1, dat1);
oPrStmt.setString(2, dat2);
oPrStmt.setString(3, dat3);
oPrStmt.setString(4, dat4);  
oPrStmt.setString(5, dat5);
oPrStmt.setString(6, dat6);
oPrStmt.setString(7, dat7);
oPrStmt.setString(8, dat8);
oPrStmt.setString(9, dat9);
oPrStmt.addBatch();
if (++count % batchSize == 0) {
oPrStmt.executeBatch();
oPrStmt.clearBatch(); 
}                
}
oPrStmt.executeBatch();
oJson.put("status","sucess");
str=oJson.toString(); 
in.close();
br.close();

System.out.println("sucessfully imported");
}
catch (Exception e) {

oJson.put("status","failure");
str=oJson.toString(); 
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
} finally {
oPrStmt = Root.EcwClosePreparedStatement(oPrStmt);
oRoot = Root.closeDbConnection(null, oRoot);
}
return str;
}
}

这是您问题的解决方案,

文件
  1. IO 不应该是异步的,因此首先 Thread-1 应该逐批读取文件并将其放入某个共享队列中。
  2. 另一个多线程线程应该读取队列的内容并将其推送到数据库中。您可以使用 java 并发包的 ExecutorService 类来实现这一点。并使用倒计时闩锁协调所有这些线程。
  3. 一旦单个线程从文件中读取了所有行,它就会返回到调用方。
  4. 处理完所有这些队列条目后,数据库处理线程将关闭,相应的倒计时闩锁也将减少,并在移动到 0 时完成。
  5. 您应该使用对实际调用方的未来响应,以便在完成所有这些线程后获得响应。

这是高级视图。

最新更新