John Marston
John Marston

Reputation: 141

File read progress

I am using java to read a TSV file that is 4gb in size and i wanted to know if there is a way for java to tell me how far it is through the task as the program is running. I'm thinking file stream might be able to tell me how many bytes it has read and i could do some simple math with that.

Upvotes: 1

Views: 1068

Answers (3)

Stephen C
Stephen C

Reputation: 719386

A plain stream or reader doesn't count the number of bytes / characters read.

I think you might be looking for ProgressMonitorInputStream.

If you don't want / need the Swing integration, then another alternative is to write a custom subclass of FilterReader or FilterInputStream that counts the characters/bytes read and provides a getter for reading the count. Then put the custom class into your input stack at the appropriate point.

Upvotes: 4

George
George

Reputation: 4109

If you read this file through HTTP, there is a header named "Content-Length" can tell you the total number of bytes you should read, then you know the progress while you are reading.

If you read the file through TCP/UDP, I guess you should write both the client and the server for file transferring, then you should send the file length first to the client, then read the file.

If you just read a local file, this is not a problem.

Upvotes: 0

Synesso
Synesso

Reputation: 39018

As you read from the stream, keep a tally of bytes read. For example, if you are reading byte arrays directly from the stream:

    long bytesReadTotal = 0L;
    int bytesRead = stream.read(bytes);
    while (bytesRead != -1) {
        bytesReadTotal += bytesRead;
        // process these bytes ...
        bytesRead = stream.read(bytes)
    }

Upvotes: 2

Related Questions