我有一个解析CSV文件的方法,并将值保存到MySQL数据库中。在这里,我逐行迭代文件,并将其存储到DB中。有没有办法利用线程并行地读写这行代码,以便快速执行?
下面是我想用多线程的方式实现的代码。
public String csvUpload(MultipartFile file){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line = "";
int header = 0;
while ((line = br.readLine()) != null) {
// TO SKIP HEADER
if(header == 0) {
header++;
continue;
}
header++;
//Use Comma As Separator
String[] csvDataSet = line.split(",");
/*
Call a Validator Method to Validate Data.
if no Errors then{
mapping to Pojo
}else{
Mapping the errors into error-List
}
once the whole file is read, then
if error-List is empty
call saveAll() and save data.
else
save the Errors into Db.
*/
}
}catch(IOException ex) {
ex.printStackTrace();
}
return "Success";
}我需要像下面这样做,使用threads.so来快速执行。
thread1 --> line 1-10
thread2 --> line 11-20线程应该并行执行下面的任务。
Call Validator Method(){
if no Errors then{
mapping to Pojo
}else{
Mapping the errors into error-List
}}
读取整个文件后,如果error-List为空,则调用saveAll()并保存数据。否则,将错误保存到Db中。
欢迎任何建议和更正。提前谢谢。
发布于 2019-02-28 02:42:08
避免逐行阅读的一种方法是使用Java7Files类,该类有一个readAllLines方法。之后,您可以向exectuorService提交可调用的任务,以便使用多个线程将其插入到DB中。
List<String> lines = Files.readAllLines(Paths.get(path), encoding);https://stackoverflow.com/questions/54912268
复制相似问题