cn.keayuan.util.IOUtils Maven / Gradle / Ivy
The newest version!
package cn.keayuan.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import cn.keayuan.util.function.BiConsumer;
import cn.keayuan.util.function.Consumer;
/**
* IO utils
*
* @author Vladislav Bauer
*/
public class IOUtils {
private IOUtils() {
throw new AssertionError();
}
/**
* Close closable object and wrap {@link IOException} with {@link RuntimeException}
*
* @param closeable closeable object
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
/**
* Close closable and hide possible {@link IOException}
*
* @param closeables closeable object
*/
public static void closeQuietly(Closeable... closeables) {
if (closeables != null) {
for (Closeable closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ignored) {
}
}
}
}
public static boolean transformQuietly(InputStream is, OutputStream os, boolean autoClose) {
try {
transform(is, os, autoClose);
return true;
} catch (IOException ignored) {
return false;
}
}
public static void transform(InputStream is, OutputStream os, boolean autoClose) throws IOException {
try {
byte[] data = new byte[1024 * 10];
int length;
while ((length = is.read(data)) != -1) {
os.write(data, 0, length);
}
os.flush();
} finally {
if (autoClose) closeQuietly(is, os);
}
}
public static void read(InputStream is, BiConsumer consumer) throws IOException {
byte[] data = new byte[1024 * 10];
int length;
while ((length = is.read(data)) != -1) {
consumer.accept(data, length);
}
}
public static byte[] read(InputStream is, boolean autoClose) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(is, os, autoClose);
return os.toByteArray();
}
public static String readToString(InputStream is, String charset, boolean autoClose) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(is, os, autoClose);
return charset == null ? os.toString() : os.toString(charset);
}
public static void readLine(InputStream is, String charset, Consumer consumer) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
String line;
while ((line = reader.readLine()) != null) {
consumer.accept(line);
}
}
}