All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xwzhou.commons.io.IOUtils Maven / Gradle / Ivy

The newest version!
package com.xwzhou.commons.io;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

import org.apache.commons.io.output.StringBuilderWriter;

import com.xwzhou.commons.lang.helper.ExceptionHelper;

public class IOUtils {

	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

	private static final int EOF = -1;

	public static final void close(final Closeable closeable) {
		if (null != closeable) {
			try {
				closeable.close();
			} catch (IOException e) {
				ExceptionHelper.throwException(e);
			}
		}
	}

	public static final void close(final Closeable closeable, final Closeable... closeables) {
		close(closeable);
		if (null == closeables || closeables.length == 0)
			return;
		for (int i = 0; i < closeables.length; i++) {
			close(closeables[i]);
		}
	}

	public static final byte[] toByteArray(final InputStream is) throws IOException {
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		copy(is, os);
		return os.toByteArray();
	}

	public static final char[] toCharArrayWriter(final InputStream is) throws IOException {
		final CharArrayWriter writer = new CharArrayWriter();
		copy(is, writer);
		return writer.toCharArray();
	}

	public static final StringBuilder toStringBuilder(final InputStream is) throws IOException {
		final StringBuilderWriter writer = new StringBuilderWriter();
		copy(is, writer);
		return writer.getBuilder();
	}

	public static final String toString(final InputStream is) throws IOException {
		final StringBuilderWriter writer = new StringBuilderWriter();
		copy(is, writer);
		return writer.toString();
	}

	public static long copy(final Reader input, final Writer output, final char[] buffer) throws IOException {
		long count = 0;
		int n;
		while (EOF != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

	public static final long copy(final InputStream is, final Writer writer) throws IOException {
		final InputStreamReader reader = new InputStreamReader(is);
		return copy(reader, writer, new char[DEFAULT_BUFFER_SIZE]);
	}

	public static final long copy(final InputStream is, final OutputStream os, final byte[] buffer) throws IOException {
		long count = 0;
		int n;
		while (EOF != (n = is.read(buffer))) {
			os.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

	public static final long copy(final InputStream is, final OutputStream os) throws IOException {
		return copy(is, os, new byte[DEFAULT_BUFFER_SIZE]);
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy