From 760af5a1d6281d38e9bba5811b82a6d2c19e0061 Mon Sep 17 00:00:00 2001 From: calvin1978 Date: Sun, 1 Jan 2017 19:52:21 +0800 Subject: [PATCH] =?UTF-8?q?#525=20=E5=8A=A0=E5=BC=BAUtils=20Modules?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=EF=BC=9AIOUtils=20=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/springside/modules/utils/io/IOs.java | 178 ++++++++++++++++++ .../modules/utils/io/StringBuilderWriter.java | 167 ++++++++++++++++ 2 files changed, 345 insertions(+) create mode 100644 modules/utils/src/main/java/org/springside/modules/utils/io/IOs.java create mode 100644 modules/utils/src/main/java/org/springside/modules/utils/io/StringBuilderWriter.java diff --git a/modules/utils/src/main/java/org/springside/modules/utils/io/IOs.java b/modules/utils/src/main/java/org/springside/modules/utils/io/IOs.java new file mode 100644 index 00000000..e5fbf4f1 --- /dev/null +++ b/modules/utils/src/main/java/org/springside/modules/utils/io/IOs.java @@ -0,0 +1,178 @@ +package org.springside.modules.utils.io; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.net.Socket; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipFile; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springside.modules.utils.text.Charsets; + +import com.google.common.annotations.Beta; + +/** + * IO相关工具集 + * + * 建议使用Apache Commons IO, 在未引入Commons IO时可以用本类做最基本的事情. + * + * 代码基本从Apache Commmons IO中化简移植, 固定encoding为UTF8. + * + * 1. 安静关闭Closeable对象的closeQuietly() + * + * 2. 读出InputStream 和 Reader内容到String的toString() + * + * 3. 读出nputStream 和 Reader内容到List的readLines() + * + * 4. 将String写到OutputStream 和 Writer的write() + * + * 5. InputStream/Reader与OutputStream/Writer之间复制的copy() + * + * @author calvin + */ +@Beta +public class IOs { + private static final Logger logger = LoggerFactory.getLogger(IOs.class); + + private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; + public static final int EOF = -1; + + private static final String CLOSE_ERROR_MESSAGE = "IOException thrown while closing Closeable."; + + /** + * 在final中安静的关闭, 不再往外抛出异常避免影响原有异常,最常用函数. 同时兼容Closeable为空未实际创建的情况. + */ + public static void closeQuietly(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + logger.warn(CLOSE_ERROR_MESSAGE, e); + } + } + } + + /** + * For JDK6 which ZipFile is not Closeable. + */ + public static void closeQuietly(ZipFile zipfile) { + if (zipfile != null) { + try { + zipfile.close(); + } catch (IOException e) { + logger.warn(CLOSE_ERROR_MESSAGE, e); + } + } + } + + /** + * For JDK6 which Socket is not Closeable. + */ + public static void closeQuietly(Socket socket) { + if (socket != null) { + try { + socket.close(); + } catch (IOException e) { + logger.warn(CLOSE_ERROR_MESSAGE, e); + } + } + } + + public static String toString(InputStream input) throws IOException { + StringBuilderWriter sw = new StringBuilderWriter(); + InputStreamReader reader = new InputStreamReader(input, Charsets.UTF_8); + copy(reader, sw, new char[DEFAULT_BUFFER_SIZE]); + return sw.toString(); + } + + public static String toString(Reader reader) throws IOException { + StringBuilderWriter sw = new StringBuilderWriter(); + copy(reader, sw, new char[DEFAULT_BUFFER_SIZE]); + return sw.toString(); + } + + public static List readLines(final Reader input) throws IOException { + final BufferedReader reader = toBufferedReader(input); + final List list = new ArrayList(); + String line = reader.readLine(); + while (line != null) { + list.add(line); + line = reader.readLine(); + } + return list; + } + + public static List readLines(final InputStream input, final Charset encoding) throws IOException { + final InputStreamReader reader = new InputStreamReader(input, Charsets.UTF_8); + return readLines(reader); + } + + + public static void write(final String data, final OutputStream output) throws IOException { + if (data != null) { + output.write(data.getBytes(Charsets.UTF_8)); + } + } + + public static void write(final String data, final Writer output) throws IOException { + if (data != null) { + output.write(data); + } + } + + public static long copy(final Reader input, final Writer output) throws IOException { + return copy(input, output, new char[DEFAULT_BUFFER_SIZE]); + } + + public static long copy(final InputStream input, final OutputStream output) throws IOException { + return copy(input, output, new byte[DEFAULT_BUFFER_SIZE]); + } + + public static void copy(final InputStream input, final Writer output, final Charset inputEncoding) + throws IOException { + final InputStreamReader in = new InputStreamReader(input, Charsets.UTF_8); + copy(in, output); + } + + public static void copy(final Reader input, final OutputStream output, final Charset outputEncoding) + throws IOException { + final OutputStreamWriter out = new OutputStreamWriter(output, Charsets.UTF_8); + copy(input, out); + out.flush(); + } + + private 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; + } + + private static long copy(final InputStream input, final OutputStream output, final byte[] buffer) + throws IOException { + long count = 0; + int n; + while (EOF != (n = input.read(buffer))) { + output.write(buffer, 0, n); + count += n; + } + return count; + } + + private static BufferedReader toBufferedReader(final Reader reader) { + return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + } +} diff --git a/modules/utils/src/main/java/org/springside/modules/utils/io/StringBuilderWriter.java b/modules/utils/src/main/java/org/springside/modules/utils/io/StringBuilderWriter.java new file mode 100644 index 00000000..232f6219 --- /dev/null +++ b/modules/utils/src/main/java/org/springside/modules/utils/io/StringBuilderWriter.java @@ -0,0 +1,167 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.springside.modules.utils.io; + +import java.io.Serializable; +import java.io.Writer; + +/** + * JDK的java.io.StringWriter使用StringBuffer,移植Commons IO使用StringBuilder的版本. + * + * {@link Writer} implementation that outputs to a {@link StringBuilder}. + *

+ * NOTE: This implementation, as an alternative to + * java.io.StringWriter, provides an un-synchronized + * (i.e. for use in a single thread) implementation for better performance. + * For safe usage with multiple {@link Thread}s then + * java.io.StringWriter should be used. + * + * @version $Id: StringBuilderWriter.java 1722253 2015-12-30 00:36:12Z ggregory $ + * @since 2.0 + */ +public class StringBuilderWriter extends Writer implements Serializable { + + private static final long serialVersionUID = -146927496096066153L; + private final StringBuilder builder; + + /** + * Constructs a new {@link StringBuilder} instance with default capacity. + */ + public StringBuilderWriter() { + this.builder = new StringBuilder(); + } + + /** + * Constructs a new {@link StringBuilder} instance with the specified capacity. + * + * @param capacity The initial capacity of the underlying {@link StringBuilder} + */ + public StringBuilderWriter(final int capacity) { + this.builder = new StringBuilder(capacity); + } + + /** + * Constructs a new instance with the specified {@link StringBuilder}. + * + *

If {@code builder} is null a new instance with default capacity will be created.

+ * + * @param builder The String builder. May be null. + */ + public StringBuilderWriter(final StringBuilder builder) { + this.builder = builder != null ? builder : new StringBuilder(); + } + + /** + * Appends a single character to this Writer. + * + * @param value The character to append + * @return This writer instance + */ + @Override + public Writer append(final char value) { + builder.append(value); + return this; + } + + /** + * Appends a character sequence to this Writer. + * + * @param value The character to append + * @return This writer instance + */ + @Override + public Writer append(final CharSequence value) { + builder.append(value); + return this; + } + + /** + * Appends a portion of a character sequence to the {@link StringBuilder}. + * + * @param value The character to append + * @param start The index of the first character + * @param end The index of the last character + 1 + * @return This writer instance + */ + @Override + public Writer append(final CharSequence value, final int start, final int end) { + builder.append(value, start, end); + return this; + } + + /** + * Closing this writer has no effect. + */ + @Override + public void close() { + // no-op + } + + /** + * Flushing this writer has no effect. + */ + @Override + public void flush() { + // no-op + } + + + /** + * Writes a String to the {@link StringBuilder}. + * + * @param value The value to write + */ + @Override + public void write(final String value) { + if (value != null) { + builder.append(value); + } + } + + /** + * Writes a portion of a character array to the {@link StringBuilder}. + * + * @param value The value to write + * @param offset The index of the first character + * @param length The number of characters to write + */ + @Override + public void write(final char[] value, final int offset, final int length) { + if (value != null) { + builder.append(value, offset, length); + } + } + + /** + * Returns the underlying builder. + * + * @return The underlying builder + */ + public StringBuilder getBuilder() { + return builder; + } + + /** + * Returns {@link StringBuilder#toString()}. + * + * @return The contents of the String builder. + */ + @Override + public String toString() { + return builder.toString(); + } +}