com.discovery.darchrow.io.IOWriteUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.discovery.darchrow.io.IOWriteUtil.java

Source

/*
 * Copyright (C) 2008 feilong
 *
 * 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.
 */
package com.discovery.darchrow.io;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.discovery.darchrow.lang.CharsetType;
import com.discovery.darchrow.util.Validator;

/**
 * ???
 * 
 * <ul>
 * <li>{@link #write(InputStream, OutputStream)} ?,,  {@code <<>>}</li>
 * <li>{@link #write(String, String)} </li>
 * <li>{@link #write(InputStream, String, String)} inputStream  ?,??fileName</li>
 * <li>{@link #write(String, String, String)} /</li>
 * <li>{@link #write(String, String, String, FileWriteMode)} </li>
 * </ul>
 * 
 * ?,? {@link #write(String, String, String, FileWriteMode)}.
 *
 * @author feilong
 * @version 1.0 Dec 23, 2013 10:23:23 PM
 * @see "org.springframework.util.StreamUtils"
 * @see "org.springframework.util.FileCopyUtils"
 * @see org.apache.commons.io.IOUtils
 * @since 1.0.0
 */
public final class IOWriteUtil {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(IOWriteUtil.class);

    /** Don't let anyone instantiate this class. */
    private IOWriteUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    /**
     * inputStream  ?( ??"/"),??fileName.
     * 
     * <h3>fileAllName ?</h3>
     * 
     * <blockquote>
     * <p>
     * {@code directoryName + "/" + fileName}
     * </p>
     * </blockquote>
     * <p>
     * .<br>
     *  ?,(?? )
     * </p>
     *
     * @param inputStream
     *            ?
     * @param directoryName
     *             ??"/"
     * @param fileName
     *            ??
     * @see com.baozun.nebulaplus.io.IOWriteUtil#write(InputStream, OutputStream)
     */
    public static void write(InputStream inputStream, String directoryName, String fileName) {
        String filePath = directoryName + "/" + fileName;

        FileUtil.createDirectory(directoryName);

        OutputStream outputStream = FileUtil.getFileOutputStream(filePath);
        write(inputStream, outputStream);
    }

    /**
     * ?,,  {@code  <<>>} .<br>
     * <b>(? <code>inputStream</code>? <code>outputStream</code>).</b>
     *
     * @param inputStream
     *            inputStream
     * @param outputStream
     *            outputStream
     * @see java.io.OutputStream#write(byte[], int, int)
     * @see #write(int, InputStream, OutputStream)
     * @see org.apache.commons.io.IOUtils#copyLarge(InputStream, OutputStream)
     */
    public static void write(InputStream inputStream, OutputStream outputStream) {
        //Just write in blocks instead of copying it entirely into Java's memory first.
        //The below basic example writes it in blocks of 10KB.
        //This way you end up with a consistent memory usage of only 10KB instead of the complete content length. 
        //Also the enduser will start getting parts of the content much sooner.
        write(IOConstants.DEFAULT_BUFFER_LENGTH, inputStream, outputStream);
    }

    /**
     * ?,,  {@code  <<>>} .<br>
     * <b>(? <code>inputStream</code>? <code>outputStream</code>).</b>
     *
     * @param bufferLength
     *            ?buffer?
     * @param inputStream
     *            inputStream
     * @param outputStream
     *            outputStream
     * @see java.io.OutputStream#write(byte[], int, int)
     * @see org.apache.commons.io.IOUtils#copyLarge(InputStream, OutputStream)
     * @see <a href="http://stackoverflow.com/questions/10142409/write-an-inputstream-to-an-httpservletresponse">As creme de la creme with
     *      regard to performance, you could use NIO Channels and ByteBuffer. Create the following utility/helper method in some custom
     *      utility class,</a>
     * @see #writeUseNIO(int, InputStream, OutputStream)
     */
    public static void write(int bufferLength, InputStream inputStream, OutputStream outputStream) {
        writeUseNIO(bufferLength, inputStream, outputStream);
    }

    /**
     * NIO API ?? ().
     *
     * @param bufferLength
     *            the buffer length
     * @param inputStream
     *            the input stream
     * @param outputStream
     *            the output stream
     * @since 1.0.8
     * @since jdk1.4
     */
    private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) {
        int i = 0;
        int sumSize = 0;
        int j = 0;

        ///2 
        //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. 

        ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
        WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);

        ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

        try {
            while (readableByteChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                j = writableByteChannel.write(byteBuffer);
                sumSize += j;
                byteBuffer.clear();
                i++;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]",
                        FileUtil.formatSize(sumSize), bufferLength, i);
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(writableByteChannel);
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(readableByteChannel);
        }
    }

    // *******************************************************************************************

    /**
     * 
     * 
     * <ul>
     * <li>?,;(?)</li>
     * <li>, , ? {@link FileWriteMode#COVER}.</li>
     * <li>?encode, {@link CharsetType#GBK}?</li>
     * </ul>
     *
     * @param filePath
     *            
     * @param content
     *            
     * @see FileWriteMode
     * @see CharsetType
     */
    public static void write(String filePath, String content) {
        String encode = null;
        write(filePath, content, encode);
    }

    /**
     * /.
     * 
     * <ul>
     * <li>?,;(?)</li>
     * <li>, , ? {@link FileWriteMode#COVER}.</li>
     * </ul>
     *
     * @param filePath
     *            
     * @param content
     *            
     * @param encode
     *            ?,isNullOrEmpty, {@link CharsetType#GBK}? {@link CharsetType}
     * @see FileWriteMode
     * @see CharsetType
     * @see #write(String, String, String, FileWriteMode)
     */
    public static void write(String filePath, String content, String encode) {
        FileWriteMode default_fileWriteMode = FileWriteMode.COVER;
        write(filePath, content, encode, default_fileWriteMode);
    }

    /**
     * .
     * 
     * <ul>
     * <li>?,, (?? )</li>
     * <li>,?  {@link FileWriteMode#APPEND}??</li>
     * </ul>
     *
     * @param filePath
     *            
     * @param content
     *            
     * @param encode
     *            ?,isNullOrEmpty, {@link CharsetType#GBK}? {@link CharsetType}
     * @param fileWriteMode
     *            ?
     * @see FileWriteMode
     * @see CharsetType
     * @see java.io.FileOutputStream#FileOutputStream(File, boolean)
     */
    public static void write(String filePath, String content, String encode, FileWriteMode fileWriteMode) {

        //TODO ? ???? 
        if (Validator.isNullOrEmpty(encode)) {
            encode = CharsetType.GBK;
        }

        // **************************************************************************8
        File file = new File(filePath);

        FileUtil.createDirectoryByFilePath(filePath);

        OutputStream outputStream = null;
        try {
            outputStream = FileUtil.getFileOutputStream(filePath, fileWriteMode);
            //TODO ? write(inputStream, outputStream);

            Writer outputStreamWriter = new OutputStreamWriter(outputStream, encode);

            Writer writer = new PrintWriter(outputStreamWriter);
            writer.write(content);
            writer.close();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("fileWriteMode:[{}],encode:[{}],contentLength:[{}],fileSize:[{}],absolutePath:[{}]",
                        fileWriteMode, encode, content.length(), FileUtil.getFileFormatSize(file),
                        file.getAbsolutePath());
            }
            outputStream.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }
}