copy InputStream To File using FileOutputStream and FileChannel - Android java.io

Android examples for java.io:InputStream

Description

copy InputStream To File using FileOutputStream and FileChannel

Demo Code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main{

    public static void copyInputStreamToFile(InputStream inputStream,
            File file) throws IOException {
        FileChannel fileChannel = null;
        FileOutputStream fileOutputStream = null;
        try {/*from   w w w.  j a  va 2s . co  m*/
            fileOutputStream = new FileOutputStream(file);
            fileChannel = fileOutputStream.getChannel();
            byte[] buffer = new byte[1024];
            while (true) {
                int read = inputStream.read(buffer);
                if (read <= 0) {
                    break;
                }
                fileChannel.write(ByteBuffer.wrap(buffer, 0, read));
            }

        } catch (IOException ex) {
            throw ex;
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (fileChannel != null)
                fileChannel.close();
            if (fileOutputStream != null)
                fileOutputStream.close();
        }

    }

}

Related Tutorials