Java FileOutputStream Write saveTo(String path, InputStream in)

Here you can find the source of saveTo(String path, InputStream in)

Description

Saves content read from input stream into a file.

License

Apache License

Parameter

Parameter Description
path path to file.
in input stream to read content from.

Declaration

public static void saveTo(String path, InputStream in) 

Method Source Code


//package com.java2s;
/*//from   w ww .j av  a  2 s .  c o m
Copyright 2009-2016 Igor Polevoy
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import java.io.*;

public class Main {
    /**
     * Saves content read from input stream into a file.
     *
     * @param path path to file.
     * @param in  input stream to read content from.
     */
    public static void saveTo(String path, InputStream in) {
        if (in == null) {
            throw new IllegalArgumentException("input stream cannot be null");
        }
        if (path == null) {
            throw new IllegalArgumentException("path cannot be null");
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            closeQuietly(out);
        }
    }

    /**
     * Saves content of byte array to file.
     *
     * @param path path to file - can be absolute or relative to current.
     * @param content bytes to save.
     */
    public static void saveTo(String path, byte[] content) {
        InputStream is = null;
        try {
            is = new ByteArrayInputStream(content);
            saveTo(path, is);
        } finally {
            closeQuietly(is);
        }
    }

    /**
     * Reads contents of the input stream fully and returns it as String. Sets UTF-8 encoding internally.
     *
     * @param in InputStream to read from.
     * @return contents of the input stream fully as String.
     * @throws IOException in case of IO error
     */
    public static String read(InputStream in) throws IOException {
        return read(in, "UTF-8");
    }

    /**
     * Reads contents of the input stream fully and returns it as String.
     *
     * @param in InputStream to read from.
     * @param charset name of supported charset to use
     * @return contents of the input stream fully as String.
     * @throws IOException in case of IO error
     */
    public static String read(InputStream in, String charset) throws IOException {
        if (in == null) {
            throw new IllegalArgumentException("input stream cannot be null");
        }
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(in, charset);
            char[] buffer = new char[1024];
            StringBuilder sb = new StringBuilder();
            int len;
            while ((len = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, len);
            }
            return sb.toString();
        } finally {
            closeQuietly(reader);
        }
    }

    /**
     * Reads file into a byte array.
     *
     * @param file file to read.
     * @return content of file.
     * @throws java.io.IOException
     */
    public static byte[] read(File file) throws IOException {
        FileInputStream is = new FileInputStream(file);
        try {
            return bytes(is);
        } finally {
            closeQuietly(is);
        }
    }

    /**
     * Closes a resource and swallows exception if thrown during a close.
     *
     * @param autoCloseable resource to close
     */
    public static void closeQuietly(AutoCloseable autoCloseable) {
        try {
            if (autoCloseable != null) {
                autoCloseable.close();
            }
        } catch (Exception ignore) {
        }
    }

    /**
     * Reads contents of the input stream fully and returns it as byte array.
     *
     * @param in InputStream to read from.
     * @return contents of the input stream fully as byte array
     * @throws IOException in case of IO error
     */
    public static byte[] bytes(InputStream in) throws IOException {
        if (in == null) {
            throw new IllegalArgumentException("input stream cannot be null");
        }
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream(1024);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            return os.toByteArray();
        } finally {
            closeQuietly(os);
        }
    }

    /**
     * @deprecated use {@link #closeQuietly(AutoCloseable)} instead. Two problems can arise if resources are not
     * closed quietly in the finally block: (1) If there are multiple close() calls, and one of the first ones throws
     * an Exception, then the following ones will never be called. (2) If an Exception is thrown inside the
     * try { ... } catch block and another Exception is thrown by a close() call in the finally { ... } block, then the
     * second Exception will hide the first one.
     */
    @Deprecated
    public static void close(Closeable c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
            // If there is an exception, the developer needs to pay attention, right? :)
            throw new RuntimeException(e);
        }
    }
}

Related

  1. saveTempFile(String xmlSource, String fileName)
  2. saveTextContentInFile(String content, File file)
  3. saveTextToFile(String fileName, String content)
  4. saveTo(InputStream in, String fileName)
  5. saveTo(String path, InputStream in)
  6. saveToBinaryFile(File dest, byte[] data)
  7. saveToDisc(final InputStream fileInputStream, final String fileUploadPath)
  8. saveToDisk(InputStream is, String filename)
  9. saveToDisk(String contents, String filename)