com.github.quartzwebui.utils.IOUtils Maven / Gradle / Ivy
The newest version!
/**
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.github.quartzwebui.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
/**
* @author quxiucheng [[email protected]]
*/
public class IOUtils {
private static Logger logger = LoggerFactory.getLogger(IOUtils.class);
public final static int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static String readFromResource(String resource) {
InputStream in = null;
try {
in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (in == null) {
in = IOUtils.class.getResourceAsStream(resource);
}
if (in == null) {
return null;
}
String text = IOUtils.read(in);
return text;
} finally {
close(in);
}
}
public static String read(InputStream in) {
InputStreamReader reader;
try {
reader = new InputStreamReader(in, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return read(reader);
}
public static String read(Reader reader) {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int n = 0;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
return writer.toString();
} catch (IOException ex) {
throw new IllegalStateException("read error", ex);
}
}
public static void close(Closeable x) {
if (x == null) {
return;
}
try {
x.close();
} catch (Exception e) {
logger.debug("close error", e);
}
}
public static byte[] readByteArrayFromResource(String resource) throws IOException {
InputStream in = null;
try {
in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (in == null) {
return null;
}
return readByteArray(in);
} finally {
close(in);
}
}
public static byte[] readByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static long copy(InputStream input, OutputStream output) throws IOException {
final int EOF = -1;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy