Java InputStream to Writer inputStreamToWriterToFile(InputStream in, File file)

Here you can find the source of inputStreamToWriterToFile(InputStream in, File file)

Description

input Stream To Writer To File

License

Apache License

Declaration

public static void inputStreamToWriterToFile(InputStream in, File file) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedWriter;
import java.io.File;

import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

public class Main {
    public static void inputStreamToWriterToFile(InputStream in, File file) throws Exception {
        String string = inputStreamToReaderToString(in);
        BufferedWriter writer = null;
        try {//from  w  w  w  .  j  av a  2s  .c om
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(string);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }

    public static String inputStreamToReaderToString(InputStream in) throws Exception {
        char[] buf = new char[4096];
        int len;

        InputStreamReader reader = null;
        StringWriter writer = null;
        try {
            reader = new InputStreamReader(in, "UTF-8");
            writer = new StringWriter();

            while ((len = reader.read(buf)) >= 0) {
                writer.write(buf, 0, len);
            }
            writer.flush();

        } finally {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
        }

        return (writer == null ? null : writer.toString());
    }
}

Related

  1. inputStreamToWriter(final InputStream in, final Writer out)