1

I'm trying to compress files inside a directory using java FileSystem. It's working fine when there are only few files, but it fails when there are more than 100 files.

This is the code which I used in my program:

Map<String, String> env = new HashMap<>();
env.put("create", "true");
URI uri = URI.create("jar:file://10.0.8.31/Shared/testFile.zip");
long bytesRead = 0;
File dir = new File("D:\\Shared\\DPXSequence");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
    for (File sourceF : dir.listFiles()) {
        Path externalFile = Paths.get(sourceF.getAbsolutePath());
        Path pathInZipfile = zipfs.getPath("/" + sourceF.getName());

        // copy a file into the zip file
        Files.copy(externalFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    }
}
catch(Exception e) {
    System.out.println("Error : "+e.toString());
}

This is the error which I'm getting:

Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space

Where I'm doing wrong? I think Files.copy() execution completing before it actually compressed and copied to the destination folder. Is that causing the issue?

admdrew
  • 3,790
  • 4
  • 27
  • 39
Nirmal Raghavan
  • 572
  • 7
  • 20
  • 1
    Maybe this [answer](http://stackoverflow.com/a/23861949/2287893) by @diego-giagio answer helps to overcome the OOM. – MZerau Aug 08 '16 at 11:06

1 Answers1

1

Either the file you are trying to copy is to big or for whatever reason System.gc() is not being activated and clearing up the memory used.

So check the following:

Input [System.gc();] after the files.copy in the method

OR

Run the java program with more memory allocated to it:

java -Xmx1024M -Xms1024M -jar jarName.jar (If its a jar) Xmx is the max amount you want to allocate (in MB with the M) and the Xms is the initial amount. You can replace the 1024 with anything you want just don't exceed your RAM on your computer.

user2494817
  • 697
  • 4
  • 12
  • Each files are around 8MB size. And there almost 5000 files to zip. No luck with `System.gc();`. I cant allocate more memory to java, It's restricted in my environment. – Nirmal Raghavan Dec 15 '13 at 11:08
  • You will have to almost do it like reading a file. Use a "buffer" and copy some over a little at a time. I am sorry, but i would not know how to implement this using the code above.. System.gc() should of worked.. oh well. – user2494817 Dec 15 '13 at 19:45