title: Java serversocket(http) reading binary data from a POST
body: <p>So, I have a webserver which handles a connection request, <strong>stores the whole request into a String</strong> (the problem relies here I believe), before doing any type of handling.</p>
  
  <pre><code>        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
  
          // Loop here until there is no more to read, but wait until the first message arrives.
          while (in.ready() || httpRequestString.isEmpty()) {
              // Read one integer at the time and cast it to a character.
              httpRequestString += (char) in.read();
  
          }
  </code></pre>
  
  <p>Then sends it to HttpRequest class to inspect it and if it is a POST, save the binary data onto a file.</p>
  
  <p>Works fine with a text file, not with a binary file which becomes corrupt.</p>
  
  <p>I know you shouldn't read binary files line by line (specially with a scanner) and write it with a printwriter, but I have to inspect the request and look for the starting and ending boundaries where the file contents are, consequently I came up with the fast temporary code, just goes to show what I have.</p>
  
  <pre><code>scanner = new Scanner(body);
  while (scanner.hasNextLine()) {
      String line = scanner.nextLine();
      if (line.equals("--" + boundary)) {
          fileName = scanner.nextLine().split("filename=")[1].replaceAll("\"", "");
          fileType = scanner.nextLine();
          scanner.nextLine(); //empty line
  
          PrintWriter fileOutput = new PrintWriter(rootFolder + File.separator + fileName);
          //FileOutputStream fileOutput1= new FileOutputStream(new File(rootFolder + File.separator + fileName));
          String prev = scanner.nextLine();
  
          while (scanner.hasNextLine()){
              String next = scanner.nextLine();
              System.out.println("reading from: " + prev);
              if (!(next.equals("--" + boundary + "--"))){
                  fileOutput.println(prev);
                  prev = next;
              }
              else {
                  fileOutput.print(prev);
                  break;
              }
          }
          fileOutput.close();
      }
  }
  scanner.close();
  </code></pre>
  
  <p>How would one store the whole request at the start, not loose any bytes on the process and be able to inspect the content and extract binary data from it ?</p>