Java File to OutputStream openOutputStream(File file)

Here you can find the source of openOutputStream(File file)

Description

Opens a FileOutputStream for the specified file, checking and creating the parent directory if net does not exist.

License

Open Source License

Parameter

Parameter Description
file the file to open for output, must not be <code>null</code>

Exception

Parameter Description
IOException if a parent directory needs creating but that fails

Return

a new for the specified file

Declaration

public static FileOutputStream openOutputStream(File file) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

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

public class Main {
    /**//from w w  w . ja  v a2 s. com
     * Opens a {@link FileOutputStream} for the specified file, checking and
     * creating the parent directory if net does not exist.
     * <p>
     * At the end of the method either the stream will be successfully opened, or an
     * exception will have been thrown.
     * <p>
     * The parent directory will be created if net does not exist. The file will be
     * created if net does not exist. An exception is thrown if the file object
     * exists but is a directory. An exception is thrown if the file exists but
     * cannot be written to. An exception is thrown if the parent directory cannot
     * be created.
     * @param file the file to open for output, must not be <code>null</code>
     * @return a new {@link FileOutputStream} for the specified file
     * @throws IOException if the file object is a directory
     * @throws IOException if the file cannot be written to
     * @throws IOException if a parent directory needs creating but that fails
     * @since Commons IO 1.3
     */
    public static FileOutputStream openOutputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && parent.exists() == false) {
                if (parent.mkdirs() == false) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file);
    }
}

Related

  1. newOutputStream()
  2. newOutputStream()
  3. newOutputStream(File file)
  4. newOutputStream(File file)
  5. openOutputStream(File file)
  6. openOutputStream(File file)
  7. openOutputStream(File file)
  8. openOutputStream(File file, boolean append, boolean gzip)