Java Heap Error for StringBuilder while reading zips

50 Views Asked by At

I have a scenario to read zip files from a server URL. But I get a Java heap error when i append the string in the stringbuilder


    public static void main(String args[]) {  
  
    String url = "https://server/test.zip";
    LOG.info("Url {}", url);
    String content = readZipFileFromRemote(url);
    System.out.println(content);
        
    }

  
    private static String readZipFileFromRemote(String remoteFileUrl) {
        StringBuilder sb = new StringBuilder();
        try {
        URL url = new URL(remoteFileUrl);
        InputStream in = new BufferedInputStream(url.openStream(), 1024);

         ZipInputStream stream = new ZipInputStream(in);
         byte[] buffer = new byte[1024];
         ZipEntry entry;
         while ((entry = stream.getNextEntry()) != null) {
             int read;
             while ((read = stream.read(buffer, 0, 1024)) >= 0) {
              sb.append(new String(buffer, 0, read));
            }
        }
      } catch (Exception e) {
                e.printStackTrace();
     }
    return sb.toString();
    }

Error


java.lang.OutOfMemoryError: Java heap space
   at java.util.Arrays.copyOf(Unknown Source) ~[?:?]
   at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source) ~[?:?]
   at java.lang.AbstractStringBuilder.append(Unknown Source) ~[?:?]
   at java.lang.StringBuilder.append(Unknown Source) ~[?:?]

Can someone help me with this?

0

There are 0 best solutions below