用JAVA块读取,Java - 按块读取文本文件

在开始处理块之前,您可以在文件中找到位于行边界的偏移量。通过将文件大小除以块数来开始偏移,并搜索直到找到行边界。然后将这些偏移量提供给多线程文件处理器。这是一个完整的示例,它使用可用处理器的数量来计算块数:

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ReadFileByChunks {

public static void main(String[] args) throws IOException {

int chunks = Runtime.getRuntime().availableProcessors();

long[] offsets = new long[chunks];

File file = new File("your.file");

// determine line boundaries for number of chunks

RandomAccessFile raf = new RandomAccessFile(file, "r");

for (int i = 1; i < chunks; i++) {

raf.seek(i * file.length() / chunks);

while (true) {

int read = raf.read();

if (read == '\n' || read == -1) {

break;

}

}

offsets[i] = raf.getFilePointer();

}

raf.close();

// process each chunk using a thread for each one

ExecutorService service = Executors.newFixedThreadPool(chunks);

for (int i = 0; i < chunks; i++) {

long start = offsets[i];

long end = i < chunks - 1 ? offsets[i + 1] : file.length();

service.execute(new FileProcessor(file, start, end));

}

service.shutdown();

}

static class FileProcessor implements Runnable {

private final File file;

private final long start;

private final long end;

public FileProcessor(File file, long start, long end) {

this.file = file;

this.start = start;

this.end = end;

}

public void run() {

try {

RandomAccessFile raf = new RandomAccessFile(file, "r");

raf.seek(start);

while (raf.getFilePointer() < end) {

String line = raf.readLine();

if (line == null) {

continue;

}

// do what you need per line here

System.out.println(line);

}

raf.close();

} catch (IOException e) {

// deal with exception

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值