68 lines
2.1 KiB
Java
68 lines
2.1 KiB
Java
package de.nclazz.commons.io;
|
|
|
|
import de.nclazz.commons.StringUtils;
|
|
import lombok.NonNull;
|
|
|
|
import java.io.*;
|
|
import java.security.MessageDigest;
|
|
|
|
public abstract class StreamUtils {
|
|
|
|
private StreamUtils() { /* no-op */ }
|
|
|
|
/**
|
|
* Pipes all the input from {@code streamIn} to {@code streamOut}.
|
|
* This method does not close any of the streams!
|
|
*
|
|
* @param streamIn InputStream
|
|
* @param streamOut OutputStream
|
|
* @throws IOException on Error
|
|
*/
|
|
public static void pipeStream(InputStream streamIn, OutputStream streamOut) throws IOException {
|
|
byte[] bytes = new byte[4096]; //TODO make configurable? maybe as a sys property?
|
|
int length;
|
|
while ((length = streamIn.read(bytes)) >= 0) {
|
|
streamOut.write(bytes, 0, length);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Loads an InputStream into a new byte array.
|
|
* This method does not close the stream after processing!
|
|
* @param stream InputStream
|
|
* @return new {@code byte[]}
|
|
*/
|
|
public static byte[] inputStreamToByteArray(InputStream stream) throws IOException {
|
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
|
byte[] buffer = new byte[4096]; //TODO make configurable? maybe as a sys property?
|
|
int length;
|
|
while((length = stream.read(buffer)) != -1) {
|
|
bos.write(buffer, 0, length);
|
|
}
|
|
return bos.toByteArray();
|
|
}
|
|
|
|
/**
|
|
* Digest an InputStream with given MessageDigest.
|
|
* The stream will not be closed after processing!
|
|
* @param stream to hash
|
|
* @param md hash algorithm
|
|
* @return new String hash
|
|
*/
|
|
public static String digestStream(@NonNull InputStream stream, @NonNull MessageDigest md) {
|
|
try {
|
|
byte[] buffer = new byte[2048];
|
|
int len;
|
|
while((len = stream.read(buffer)) != -1) {
|
|
md.update(buffer, 0, len);
|
|
}
|
|
byte[] digest = md.digest();
|
|
return StringUtils.toHex(digest);
|
|
}catch(Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
|
|
}
|