Limiting upload speed on Java?

后端 未结 3 1711
野的像风
野的像风 2020-12-30 15:59

I\'d like to programmatically limit an upload or download operation in Java. I would assume that all I\'d need to do was do check how fast the upload is going and insert

3条回答
  •  礼貌的吻别
    2020-12-30 16:21

    This is an old post, but how about this:

    import com.google.common.util.concurrent.RateLimiter;
    import java.io.IOException;
    import java.io.OutputStream;
    
    public final class ThrottledOutputStream extends OutputStream {
        private final OutputStream out;
        private final RateLimiter rateLimiter;
    
        public ThrottledOutputStream(OutputStream out, double bytesPerSecond) {
            this.out = out;
            this.rateLimiter = RateLimiter.create(bytesPerSecond);
        }
    
        public void setRate(double bytesPerSecond) {
            rateLimiter.setRate(bytesPerSecond);
        }
    
        @Override
        public void write(int b) throws IOException {
            rateLimiter.acquire();
            out.write(b);
        }
    
        @Override
        public void write(byte[] b) throws IOException {
            rateLimiter.acquire(b.length);
            out.write(b);
        }
    
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            rateLimiter.acquire(len);
            out.write(b, off, len);
        }
    
        @Override
        public void flush() throws IOException {
            out.flush();
        }
    
        @Override
        public void close() throws IOException {
            out.close();
        }
    }
    

    Depends on Guava, specifically the RateLimiter.

提交回复
热议问题