title: Most Robust way of reading a file or stream using Java (to prevent DoS attacks)
body: <p>Currently I have the below code for reading an <code>InputStream</code>. I am storing the whole file into a <code>StringBuilder</code> variable and processing this string afterwards.</p>
  
  <pre><code>public static String getContentFromInputStream(InputStream inputStream)
  // public static String getContentFromInputStream(InputStream inputStream,
  // int maxLineSize, int maxFileSize)
  {
  
      StringBuilder stringBuilder = new StringBuilder();
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
      String lineSeparator = System.getProperty("line.separator");
      String fileLine;
  
      boolean firstLine = true;
      try {
          // Expect some function which checks for line size limit.
          // eg: reading character by character to an char array and checking for
          // linesize in a loop until line feed is encountered.
          // if max line size limit is passed then throw an exception
          // if a line feed is encountered append the char array to a StringBuilder
          // after appending check the size of the StringBuilder
          // if file size exceeds the max file limit then throw an exception
  
          fileLine = bufferedReader.readLine();
  
          while (fileLine != null) {
              if (!firstLine) stringBuilder.append(lineSeparator);
              stringBuilder.append(fileLine);
              fileLine = bufferedReader.readLine();
              firstLine = false;
          }
      } catch (IOException e) {
          //TODO : throw or handle the exception
      }
      //TODO : close the stream
  
      return stringBuilder.toString();
  
  }
  </code></pre>
  
  <p>The code went for a review with the Security team and the following comments were received:</p>
  
  <ol>
  <li><p><code>BufferedReader.readLine</code> is susceptible to DOS (Denial of Service) attacks (line of infinite length, huge file containing no line feed/carriage return)</p></li>
  <li><p>Resource exhaustion for the <code>StringBuilder</code> variable (cases when a file containing data greater than the available memory)</p></li>
  </ol>
  
  <p>Below are the solutions I could think of: </p>
  
  <ol>
  <li><p>Create an alternate implementation of <code>readLine</code> method (<code>readLine(int limit)</code>), which checks for the no. of bytes read and if it exceeds the specified limit, throw a custom exception.</p></li>
  <li><p>Process the file line by line without loading the file in entirety. (pure non-Java solution :) )</p></li>
  </ol>
  
  <p>Please suggest if there are any existing libraries which implement the above solutions.
  Also suggest any alternate solutions which offer more robustness or are more convenient to implement than the proposed ones. Though performance is also a major requirement, security comes first.</p>