title: Copy InputStream, abort operation if size exceeds limit
body: <p>I tried to copy an InputStream to a File, and abort the copy if the size of InputStream is greater than 1MB.
  In Java7, I wrote code as below:</p>
  
  <pre><code>public void copy(InputStream input, Path target) {
      OutputStream out = Files.newOutputStream(target,
              StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
      boolean isExceed = false;
      try {
          long nread = 0L;
          byte[] buf = new byte[BUFFER_SIZE];
          int n;
          while ((n = input.read(buf)) &gt; 0) {
              out.write(buf, 0, n);
              nread += n;
              if (nread &gt; 1024 * 1024) {// Exceed 1 MB
                  isExceed = true;
                  break;
              }
          }
      } catch (IOException ex) {
          throw ex;
      } finally {
          out.close();
          if (isExceed) {// Abort the copy
              Files.deleteIfExists(target);
              throw new IllegalArgumentException();
          }
      }}
  </code></pre>
  
  <ul>
  <li>First question: is there any better solution for it? </li>
  <li>Second question: my other solution - Before the copy operation, I calculate the size of this InputStream. So I copy the InputStream to <code>ByteArrayOutputStream</code> then get <code>size()</code>. But the problem is InputStream may not <code>markSupported()</code>, so the InputStream cannot be reused in a copy file operation.</li>
  </ul>