gpt4 book ai didi

java - 在Java中以一定速率读取文件

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:08 25 4
gpt4 key购买 nike

是否有关于如何以特定速率读取长文件的文章/算法?

假设我不想在发出读取时传递 10 KB/秒。

最佳答案

一个简单的解决方案,通过创建一个 ThrottledInputStream。

应该这样使用:

        final InputStream slowIS = new ThrottledInputStream(new BufferedInputStream(new FileInputStream("c:\\file.txt"),8000),300);

300 是每秒的千字节数。 8000 是 BufferedInputStream 的 block 大小。

这当然应该通过实现 read(byte b[], int off, int len) 来概括,这将使您免于大量的 System.currentTimeMillis() 调用。每次读取一个字节都会调用 System.currentTimeMillis() 一次,这会导致一些开销。还应该可以存储无需调用 System.currentTimeMillis() 即可安全读取的字节数。

一定要在两者之间放置一个 BufferedInputStream,否则 FileInputStream 将以单个字节而不是 block 进行轮询。这将减少 CPU从 10% 加载到几乎为 0。您将面临超出数据速率的风险,超出 block 大小中的字节数。

import java.io.InputStream;
import java.io.IOException;

public class ThrottledInputStream extends InputStream {
private final InputStream rawStream;
private long totalBytesRead;
private long startTimeMillis;

private static final int BYTES_PER_KILOBYTE = 1024;
private static final int MILLIS_PER_SECOND = 1000;
private final int ratePerMillis;

public ThrottledInputStream(InputStream rawStream, int kBytesPersecond) {
this.rawStream = rawStream;
ratePerMillis = kBytesPersecond * BYTES_PER_KILOBYTE / MILLIS_PER_SECOND;
}

@Override
public int read() throws IOException {
if (startTimeMillis == 0) {
startTimeMillis = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long interval = now - startTimeMillis;
//see if we are too fast..
if (interval * ratePerMillis < totalBytesRead + 1) { //+1 because we are reading 1 byte
try {
final long sleepTime = ratePerMillis / (totalBytesRead + 1) - interval; // will most likely only be relevant on the first few passes
Thread.sleep(Math.max(1, sleepTime));
} catch (InterruptedException e) {//never realized what that is good for :)
}
}
totalBytesRead += 1;
return rawStream.read();
}
}

关于java - 在Java中以一定速率读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/872496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com