I need to send data packets to a client, and I need to send them as chunks of 512 bytes (last packet can be smaller than that). I have a file on my server folder but I'm not sure how can I read this file in chunks of 512 bytes, so I can insert them into to a byte array and send them to the client. I also need to remember where I stopped the last time (current byte location in the file) so I will know from where to read the data inorder to make the next data packet.
I found a solution but I think it's bad:
FileInputStream fin = new FileInputStream("filename")
byte[] newPacketByteArray = new byte[512];
fin.read(newPacketByteArray);
Now for the main problem, I don't close the FileInputStream until the client receive all the packets, that's because i only send the next packet when the clients reply that he got my n-th packet, so meanwhile all this time the FileInputStream is remaining open, because if i will close it i won't know how to get to the last byte location (i didn't see any option in the fileInputStream API to get to a specific location) .
I close it only after the client tells me that he got the last packet. Few question:
- Is it a bad solution? If it is, what is the best way to read chunks of 512 bytes from a file in my server and insert them into a byte[] array? Remember that I need to know where I stopped in the last time (the location of the next byte in the file) so I could send the next new data packet.
If my solution is OK, then please answer:
If few clients wishes to get the same file and there are few FileInputStream objects who read this file (perhaps simultaneously ), will it cause any problems?
Eclipse is shouting at me (yellow sign in that method) because I only close the fileInputStream if the client received all packets
thanks alot for your help