Here is a short example for copying a file with in memory caching:
try {
Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
Path target = Paths.get("targetfile");
// copy with in memory caching
// read all bytes to memory
byte[] data = Files.readAllBytes(source);
// write bytes from memory to target file
Files.write(target, data);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
And the same example without in memory caching:
try {
Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
Path target = Paths.get("targetfile");
// copy without in memory caching
Files.copy(source, target);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
The important difference is, that in the first case, the complete contents of the file is read to a byte array, which is stored in memory. Depending on the size of the file, this can be really bad. In the second case, the copying operation knows the source and the target and is therefore able to copy the file in small parts until the file is copied completely. For example, one can always copy 2048 bytes at a time, like in the accepted answer to the linked question.