Reading a file in chunks?

I know how to read a file bytes, but I can not find an example of how to read it in pieces of bytes. I have an array of bytes and I want to read a 512 byte file and send them through the socket.

I tried to read the total number of bytes of the file and then subtract 512 bytes, until I received a fragment that was less than 512 bytes, and signaled EOF and the end of the transfer.

I am trying to implement TFTP where data is sent in 512 bytes.

Anyway, thanks for the example.

+2
source share
3 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) { ... } 
+5
source

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

something like: you can wrap the input stream in a BufferedInputStream if you want to guarantee a lock of 512 bytes (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); } 
+6
source

Using an InputStream , you can read in a given size array and limit reading to that size.

Read here: http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

-1
source

All Articles