title: Encrypting a large file with AES using JAVA
body: <p>I've tested my code with files less than this(10mb, 100mb, 500mb) and the encryption works. However, I run in to problems with files greater than 1gb.
  I've generated a large file (about 2gb) and I want to encrypt it with AES using JAVA, but I'm running into this error:</p>
  
  <p>"Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"</p>
  
  <p>I've tried increasing available memory by using -Xmx8G, but no dice.
  Part of my code is as follows</p>
  
  <pre><code>    File selectedFile = new File("Z:\\dummy.txt");         
      Path path = Paths.get(selectedFile.getAbsolutePath());       
      byte[] toencrypt = Files.readAllBytes(path);       
      byte[] ciphertext = aesCipherForEncryption.doFinal(toencrypt);
      FileOutputStream fos = new FileOutputStream(selectedFile.getAbsolutePath());
      fos.write(ciphertext);
      fos.close();
  </code></pre>
  
  <p>As far as I can tell, the reason it is behaving this way, is that it is trying to read the whole file at once, encipher it, and store it into another byte array instead of buffering and streaming it in. Can anyone help me with some code tips?</p>
  
  <p>I am a beginner to coding, so I don't really know much, any help will be appreciated.</p>