Java InputStream save to file

Description

Java InputStream save to file

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {

   public static void main(String args[]) throws IOException {
      String tmp = "abcde";
      byte b[] = tmp.getBytes();
      InputStream input1 = new ByteArrayInputStream(b);

      inputStream2File(input1, new File("Main.java"));

   }//from w  w w . j a  v  a2s .  c  o m

   public static void inputStream2File(InputStream stream, File f) throws IOException {
      f.getParentFile().mkdirs();
      FileOutputStream out = new FileOutputStream(f);
      inputStream2OutputStream(stream, out);
   }

   public static void inputStream2OutputStream(InputStream stream, OutputStream out) throws IOException {
      int readedBytes;
      byte[] buf = new byte[1024];
      while ((readedBytes = stream.read(buf)) > 0) {
         out.write(buf, 0, readedBytes);
      }
      stream.close();
      out.close();
   }

}



PreviousNext

Related