Thursday, June 7, 2012

Java Standalone method to create a File from an InputStream

This method can be used to save any type of file (image, pdf...) for which you have the InputStream:

 public void createLocalCopy(String localFileName,InputStream iStream) throws IOException{
  OutputStream outStream = new FileOutputStream("C:\\Users\\MYFILE\\"+localFileName);
        try{
        System.out.println("making a local copy="+localFileName);
        byte[] buffer = new byte[1024];
        int len;
        while((len = iStream.read(buffer)) >= 0)
         outStream.write(buffer, 0, len);
        outStream.flush();
        outStream.close();
        iStream.close();
        }catch(Exception e)
        {
         outStream.flush();
         outStream.close();
         iStream.close();
        System.out.println("ERROR IN MAKING LOCAL COPY "+localFileName+", ERROR MSG = "+e.getMessage());
        }
        System.out.println("iStream====="+iStream);
 }