-2

I have a file in the jar file that I need to copy and store that file in a directory. What java api can I use to read/write file at the same time without having to cache it in memory first?

I know how to individually copy a file from jar and then write to a file but its caching it in memory first.

The below answer looks like is not caching in memory but I want to know the difference between caching vs non-caching in memory?

How to copy files out of the currently running jar

Community
  • 1
  • 1
fscore
  • 2,567
  • 7
  • 40
  • 74

1 Answers1

2

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.

Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51
  • In terms "allocate zero memory" this is not an answer (here allocation is hidden), but asker must understand this – Jacek Cz Sep 13 '15 at 18:32