package net.sourceforge.fenixedu.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import pt.utl.ist.fenix.tools.util.FileUtils; public class StreamUtils { private static final int DEFAULT_BUFFER_SIZE = 1024; public static byte[] readInputStream(final InputStream inputStream) { byte[] result = null; if (inputStream != null) { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { try { FileUtils.copy(inputStream, byteArrayOutputStream); byteArrayOutputStream.flush(); result = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } finally { try { inputStream.close(); byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static byte[] consumeFile(final File file) { FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(file); return readInputStream(fileInputStream); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public static int copyStream(InputStream source, OutputStream target) throws IOException { return copyStream(source, target, DEFAULT_BUFFER_SIZE); } public static int copyStream(InputStream source, OutputStream target, int bufferSize) throws IOException { int countBytesRead = -1; int totalBytes = 0; byte[] bufferCopy = new byte[bufferSize]; while ((countBytesRead = source.read(bufferCopy)) != -1) { target.write(bufferCopy, 0, countBytesRead); totalBytes += countBytesRead; } target.flush(); return totalBytes; } }