Read file at a certain rate in Java

前端 未结 6 617
梦谈多话
梦谈多话 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条回答
  •  情深已故
    2021-01-05 11:38

    It depends a little on whether you mean "don't exceed a certain rate" or "stay close to a certain rate."

    If you mean "don't exceed", you can guarantee that with a simple loop:

     while not EOF do
        read a buffer
        Thread.wait(time)
        write the buffer
     od
    

    The amount of time to wait is a simple function of the size of the buffer; if the buffer size is 10K bytes, you want to wait a second between reads.

    If you want to get closer than that, you probably need to use a timer.

    • create a Runnable to do the reading
    • create a Timer with a TimerTask to do the reading
    • schedule the TimerTask n times a second.

    If you're concerned about the speed at which you're passing the data on to something else, instead of controlling the read, put the data into a data structure like a queue or circular buffer, and control the other end; send data periodically. You need to be careful with that, though, depending on the data set size and such, because you can run into memory limitations if the reader is very much faster than the writer.

提交回复
热议问题