Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Read file by chunks?

I know how to read a file by bytes but cannot find a example how to read it in chunks of bytes. I have a byte array, and i want to read the file by 512bytes and send them over a socket.

I have tried by reading total bytes of file and then subtracting 512 bytes until i got a chunk that was less than 512 bytes and signaled EOF and end of transfer.

I am trying to implement a TFTP, where data is sent in 512 byte chunks.

Anyhow would be thankful for a example.

like image 785
Sterling Duchess Avatar asked Mar 06 '12 17:03

Sterling Duchess


People also ask

How to read a file in chunks in Java?

Java FileInputStream reading file by text chunksi = fis. read(buf); The read method reads up to b. length bytes of data from this the stream into the provided array of bytes.


2 Answers

You ... read 512 bytes at a time.

char[] myBuffer = new char[512];
int bytesRead = 0;
BufferedReader in = new BufferedReader(new FileReader("foo.txt"));
while ((bytesRead = in.read(myBuffer,0,512)) != -1)
{
    ...
}
like image 198
Brian Roach Avatar answered Oct 04 '22 03:10

Brian Roach


You can use the appropriate read() method from the input stream, for example FileInputStream supports a read(byte[]) to read a chunk of bytes.

something like: You may want to wrap the input stream in a BufferedInputStream if you wanted to guarantee 512 byte blocks (the constructor takes a block size argument).

byte[] buffer = new byte[512];
FileInputStream in = new FileInputStream("some_file");
int rc = in.read(buffer);
while(rc != -1)
{
  // rc should contain the number of bytes read in this operation.
  // do stuff...

  // next read
  rc = in.read(buffer); 
}
like image 22
Nim Avatar answered Oct 04 '22 05:10

Nim