Java File to OutputStream openOutputStream(File file, boolean append, boolean gzip)

Here you can find the source of openOutputStream(File file, boolean append, boolean gzip)

Description

open Output Stream

License

Apache License

Declaration

public static OutputStream openOutputStream(File file, boolean append, boolean gzip) throws IOException 

Method Source Code


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

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

import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;

public class Main {
    public static final int COMPRESSION_BUFFER_SIZE = 4096;
    public static final int COMPRESSION_LEVEL = Deflater.BEST_COMPRESSION;

    public static OutputStream openOutputStream(File file, boolean append, boolean gzip) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }/*w ww.  j  a  v a  2  s  . co m*/
            if (!file.canWrite()) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }
        }
        if (gzip) {
            return new GZIPOutputStream(new FileOutputStream(file, append), COMPRESSION_BUFFER_SIZE) {
                {
                    def.setLevel(COMPRESSION_LEVEL);
                };
            };
        }
        return new FileOutputStream(file, append);
    }
}

Related

  1. newOutputStream(File file)
  2. openOutputStream(File file)
  3. openOutputStream(File file)
  4. openOutputStream(File file)
  5. openOutputStream(File file)
  6. openOutputStream(File file, int bufferSize)
  7. openOutputStream(String filePath)
  8. openOutputStream(String outputName)
  9. outStream(final File aFile)