title: How to copy binary files byte-for-byte
body: <p>I am currently trying to solve one problem for reading and writing files in Java.</p>
  
  <p>So the task is, I am directly getting the InputStream object of file which I want to read (I don't have actual file just the InputStream object) and from this object I want to recreate the original file.</p>
  
  <p>I was trying to read the data from file byte by byte and write the same in anather file.</p>
  
  <p>But it is only working for .txt files not for doc, docx, PDF files. I haven't checked for rest of the non .txt format but I want it work for all the formats. </p>
  
  <p>For Non txt formats the files are getting generated but content from it is not visible.</p>
  
  <p>So my question is How can I recreate the file using just InputStream object for all types file format.</p>
  
  <p>Below is the sample code that I have been using to write the file. </p>
  
  <pre><code>    File file = new File("/home/sumit/Documents/newAbc.docx");
      File fileAbc = new File("/home/sumit/Documents/abc.docx");
      InputStream inputStream = new FileInputStream(fileAbc); // this is just for this sample code snippet but orginally I already have InputStream object.
      // if file doesnt exists, then create it
      if (!file.exists()) {
          file.createNewFile();
      }
  
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
  
      int data = inputStream.read();
      while(data != -1) {
        //do something with data...
        bw.write(data);       
        data = inputStream.read();
  
      }
      inputStream.close();
      bw.close();
  </code></pre>
  
  <p>Above code is getting properly compiled and executed but the created file is not displaying content properly.</p>
  
  <p>When searched I found I can not directly read Doc, PDf etc. from here: <a href="https://stackoverflow.com/questions/16682942/reading-docx-file-in-java">Reading .docx file in java</a></p>
  
  <p>but from <a href="http://poi.apache.org/" rel="nofollow noreferrer">http://poi.apache.org/</a> POI library I did not find anything that will tell me how to write into file using InputStream.</p>
  
  <p>Does anyone know how above problem can be solved? </p>