tttt

本文介绍了一个限速InputStream的实现方式,通过控制数据读取的速度来限制带宽使用。该实现覆盖了InputStream的主要方法,并增加了设置读取速度的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
* {@inheritDoc}
*/
@Override
public int read() throws IOException {
return in.read();
}

/**
* {@inheritDoc}
*/
@Override
public int read(byte b[]) throws IOException {
return this.read(b, 0, b.length);
}

/**
* {@inheritDoc}
*/
@Override
public int available() throws IOException {
return in.available();
}

/**
* {@inheritDoc}
*/
@Override
public int read(byte b[], int off, int len) throws IOException {
startTimeStamp = System.currentTimeMillis();
int readSize = in.read(b, off, len);
endTimeStamp = System.currentTimeMillis();
readAdd = readAdd + readSize;
usingTime = usingTime + (endTimeStamp - startTimeStamp);
if (readAdd > limit) {
readAdd = 0;
usingTime = 0L;
if (usingTime < MAX_SLEEP_TIME) {
startTimeStamp = 0L;
endTimeStamp = 0L;
try {
Thread.sleep(MAX_SLEEP_TIME - usingTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
}
}
}
return readSize;
}

/**
* {@inheritDoc}
*/
@Override
public long skip(long n) throws IOException {
return in.skip(n);
}

/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
in.close();
}

/**
* {@inheritDoc}
*/
@Override
public synchronized void mark(int readlimit) {
in.mark(readlimit);
}

/**
* {@inheritDoc}
*/
@Override
public synchronized void reset() throws IOException {
in.reset();
}

/**
* {@inheritDoc}
*/
@Override
public boolean markSupported() {
return in.markSupported();
}

/**
* 设置流读取速度
*
* @param limit 读取速度,单位byte
* @exception IllegalArgumentException 当设置限流速度limit为非正数时抛出此异常
*/
public void setLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit size <= 0");
}
this.limit = limit;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值