I'm studying streams and networking and I'm trying a simple program to exchange files between server and client. I found this post very useful.
This is my code that is almost identical:
These are my doubts:
1)What is the best approach to read data from the stream? The first one or the alternative one?
2)What is the recommended size for the buffer?
3)Finally (I know that is a stupid question but I don't get it) when I using the method readUTF how does it know exactly when file name end and when data file start? The writeUTF method insert markers?
Reading the whole file into memory is a risky strategy, since if the file is very large then your program may run out of memory. It's even possible for files to be larger than Integer.MAX_VALUE, in which case your program would truncate the file.
The buffer size? That depends on a variety of things which are specific to your environment. Once you get the code working you could try different values and see what difference they make.
As for exactly how readUTF and writeUTF work, I have no idea. And you don't need to know either, all you need to know is that they do what the documentation says. However if you really want to know, you could look at the source code. You can find it in the src.zip file which is in your Java install directory.
Joined: Jan 14, 2014
Thank Paul for your attention and help.
Could you do a small example of how to do not load the whole file into memory? And sorry, what about the protocol to be used for client-server communication? I have seen that often uses the type FileName, FileLength and FileData.
The author of the code in the linked post read data from the socket with but also the commented out seems to work properly The first one give you more control over the data read but there are other reasons to prefer one rather then the other one?