0

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?

8
  • Does this answer your question? How to increase Heap size of JVM Commented Oct 3, 2023 at 11:10
  • Not sure, I am running this as a Kubernetes cron job. It works alright in tomcat in my local machine Commented Oct 3, 2023 at 11:34
  • Then in crontab, edit and add that flag. Commented Oct 3, 2023 at 11:37
  • If this is Kubernetes, what are the requests/limits configured for your container/pod and how much resources are available on your Node(s)? Commented Oct 3, 2023 at 11:46
  • 1
    Why can't you output the string incrementally instead of first building the full string and then printing it? Commented Oct 3, 2023 at 13:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.