JAVA 按行处理大文件的方法 [多线程]
前一篇文章讲述了单线程处理大文件的方法,虽然解决了内存装不下的问题但是依然存在效率不高的问题。这篇文章介绍的是Java中多线程处理大文件的一种方法,如有疑问欢迎各位大神垂询,我们相互帮助、共同学习。
如果想看单线程处理大文件的那边文章请移步:Java 按行处理大文件的方法 [单线程]
一、问题的提出
按照单线程解决Java处理大文件的思路将文件分片读取,这样解决的方法效率不高。如下例:
- 代码
private static void handleInternal(List<String> lines, int index) {
File file = new File("C:\\Users\\Mr-Leaf\\Desktop\\test_new.csv") ;
StringBuilder sb = new StringBuilder() ;
for(String line : lines) {
sb.append(line + "\n") ;
}
//直接写成新文件
write(file, sb.toString()) ;
}
/**
* <p>功能: 写入文件</p>
* @param string
*/
protected static void write(File file, String str) {
try {
FileUtils.writeStringToFile(file, str , "utf-8", true);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>功能: 分片读取文件</p>
* @param file 要读取的文件
* @param encoding 编码格式
* @param startLine 开始读取的行数
* @param size 要读取的量
* @return
* @throws IOException
*/
public static List<String> copyToLines(File file, String encoding, int startLine,
int size) throws IOException
{
List<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
try
{
String line = null;
int lineNum = 0;
if (startLine < 1) startLine = 1;
while ((line = reader.readLine()) != null)
{
lineNum++;
if (startLine > 0 && lineNum < startLine) continue;
if (size > 0 && (lineNum - startLine) >= size) break;
lines.add(line);
}
}
finally
{
if (reader != null) reader.close();
}
return lines;
}
public static void handle(File file) throws IOException {
int index = 1 ;
List<String> lines = copyToLines(file, "utf-8", index, 20000) ;
while(!CollectionTools.isEmpty(lines)) {
handleInternal(lines, index) ;
System.out.println("正在处理" + index