Android InputStream Save saveInputStreamAsFile(InputStream inputStream, File target)

Here you can find the source of saveInputStreamAsFile(InputStream inputStream, File target)

Description

save Input Stream As File

Declaration

public static void saveInputStreamAsFile(InputStream inputStream,
            File target) throws IOException 

Method Source Code

//package com.java2s;

import java.io.Closeable;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Main {
    public static void saveInputStreamAsFile(InputStream inputStream,
            File target) throws IOException {
        final FileOutputStream fos = new FileOutputStream(target);
        writeFile(inputStream, fos);//from  ww w. j ava2s  .  com
        closeIOStream(fos);
        closeIOStream(inputStream);
    }

    public static void writeFile(String filepath, String text) {
        OutputStreamWriter wr = null;
        try {
            File file = new File(filepath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            wr = new OutputStreamWriter(new FileOutputStream(filepath,
                    false), "UTF8");
            wr.write(text);
            wr.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wr != null) {
                try {
                    wr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void writeFile(InputStream inputStream,
            OutputStream outputStream) throws IOException {
        final byte[] buf = new byte[10240];
        int len;
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.flush();
        closeIOStream(outputStream);
        closeIOStream(inputStream);
    }

    public static void closeIOStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. writerFromInputStream(InputStream stream, String path, String fileName)
  2. writeFile(File outputFile, InputStream inputStream)
  3. saveFile(Context context, String fileName, InputStream inputStream)
  4. writeXmlToTempFile(InputStream xmlStream, String filePath, String closingTag)
  5. writeToString(InputStream stream)
  6. saveStream(InputStream is, String savePath)
  7. saveTmpFile(InputStream is)
  8. toBase64OutputStream(InputStream is, OutputStream os)
  9. toOutputStream(InputStream is, OutputStream os)