copy Input Stream to File - Java java.io

Java examples for java.io:InputStream Read

Description

copy Input Stream to File

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
    public static void copyInputStreamtoFile(InputStream stream, File file) {
        try {/*from ww w .j a va 2s .  co m*/
            file.createNewFile();
            FileWriter out = new FileWriter(file, false);
            out.write(getInputStreamContent(stream));
            out.close();
        } catch (IOException ex) {
            throw new RuntimeException("Error read SQL script", ex);
        }

    }

    public static String getInputStreamContent(InputStream stream)
            throws IOException {
        InputStreamReader in = null;
        StringBuffer buf = null;
        try {
            buf = new StringBuffer();
            in = new InputStreamReader(stream);
            int c;
            while ((c = in.read()) != -1) {
                buf.append((char) c);
            }
        } catch (FileNotFoundException fileNotFounfEx) {
            throw fileNotFounfEx;
        } catch (IOException ioEx) {
            throw ioEx;
        } finally {
            in.close();
        }

        return buf.toString();
    }
}

Related Tutorials