What's the best strategy for reading and writing binary files of unknown size in Java? I know in languages like C/C++ you prompt the OS for the page-size and use that for efficient binary reads and writes but I'm assuming that's not available in Java or that it will make the program non-portable.
So is there an efficient array size for reading and writing binary files in Java?
Gerard Gauthier wrote:Is the above correct for a PDF file? Is it correct for a binary file?
Well, a PDF file is a binary file. And yes, it is correct. At least, I think it is.
However it copies one byte at a time. Some people might be concerned about that and wonder if using a buffer of larger than one byte would be better -- especially since PDF files of megabyte size aren't uncommon these days.
But my feeling is that Files.copy(Path, OutputStream) is the best way to do it. Why? Because you don't have to write any code which might accidentally leave off the last few bytes or something, and you don't have to download code from possibly dodgy tutorials.
And I notice that the document for that Files.copy method mentions that you should flush the output stream if you can -- the tutorial code doesn't do that, but maybe it doesn't matter.