code: protected void copyStream(File outputDirectory,
                                InputStream stream,
                                String targetFileName) throws IOException
      {
          File resourceFile = new File(outputDirectory, targetFileName);
          BufferedReader reader = null;
          Writer writer = null;
          try
          {
              reader = new BufferedReader(new InputStreamReader(stream, ENCODING));
              writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));
  
              String line = reader.readLine();
              while (line != null)
              {
                  writer.write(line);
                  writer.write('\n');
                  line = reader.readLine();
              }
              writer.flush();
          }
          finally
          {
              if (reader != null)
              {
                  reader.close();
              }
              if (writer != null)
              {
                  writer.close();
              }
          }
      }
docs: Helper method to copy the contents of a stream to a file.
  @param outputDirectory The directory in which the new file is created.
  @param stream The stream to copy.
  @param targetFileName The file to write the stream contents to.
  @throws IOException If the stream cannot be copied.