Read file at a certain rate in Java

前端 未结 6 595
梦谈多话
梦谈多话 2021-01-05 10:44

Is there an article/algorithm on how I can read a long file at a certain rate?

Say I do not want to pass 10 KB/sec while issuing reads.

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 11:29

    You can use a RateLimiter. And make your own implementation of the read in InputStream. An example of this can be seen bellow

    public class InputStreamFlow extends InputStream {
        private final InputStream inputStream;
        private final RateLimiter maxBytesPerSecond;
    
        public InputStreamFlow(InputStream inputStream, RateLimiter limiter) {
            this.inputStream = inputStream;
            this.maxBytesPerSecond = limiter;
        }
    
        @Override
        public int read() throws IOException {
            maxBytesPerSecond.acquire(1);
            return (inputStream.read());
        }
    
        @Override
        public int read(byte[] b) throws IOException {
            maxBytesPerSecond.acquire(b.length);
            return (inputStream.read(b));
        }
    
        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            maxBytesPerSecond.acquire(len);
            return (inputStream.read(b,off, len));
        }
    }
    

    if you want to limit the flow by 1 MB/s you can get the input stream like this:

    final RateLimiter limiter = RateLimiter.create(RateLimiter.ONE_MB); 
    final InputStreamFlow inputStreamFlow = new InputStreamFlow(originalInputStream, limiter);
    

提交回复
热议问题