Java FileOutputStream Create writeFile(InputStream stream, File to)

Here you can find the source of writeFile(InputStream stream, File to)

Description

Create a file with the contents of this data stream.

License

Open Source License

Parameter

Parameter Description
stream the data stream. You must close it afterward.

Declaration

public static void writeFile(InputStream stream, File to) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;

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

public class Main {
    /**//from   ww w . ja va2  s.c  o m
     * Create a file with the contents of this data stream.
     * 
     * @param stream
     *            the data stream. You must close it afterward.
     */
    public static void writeFile(InputStream stream, File to) throws IOException {
        if (to.exists()) {
            throw new IOException("File '" + to.getAbsolutePath() + "' already exists.");
        }

        File parent = to.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
            if (!parent.exists()) {
                throw new IOException("Can't create parent directory for '" + to.getAbsolutePath() + "'");
            }
        }

        OutputStream out = null;
        try {
            out = new FileOutputStream(to);
            byte[] buffer = new byte[8192];
            int howMany;
            while (-1 != (howMany = stream.read(buffer))) {
                out.write(buffer, 0, howMany);
            }
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related

  1. writeFile(InputStream inputFile, String path, String fullFileName)
  2. writeFile(InputStream inputStream, String filename, long lastModified)
  3. writeFile(InputStream is, File file)
  4. writeFile(InputStream is, File outFile)
  5. writeFile(InputStream srcStream, File destFile)
  6. writeFile(List data, String filename)
  7. writeFile(String directoryPath, String filename, byte[] bytes)
  8. writeFile(String f, String s)
  9. writeFile(String file, byte[]... data)