import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamIUtils {
/**
* 读取输入流并转换为字节数组
*
* @param inputStream 输入流
* @return 转换后的字节数组
* @throws Exception 抛出异常
*/
public static byte[] readStream2Bytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
copyStream(inputStream, byteArrayOutputStream, 102400);
return byteArrayOutputStream.toByteArray();
}
/**
* 复制流中的数据到输出流,最多复制指定字节数的数据。
*
* @param inputStream 输入流,不能为null
* @param outputStream 输出流,不能为null
* @param byteCount 最大复制字节数
* @return 返回复制的总字节数
* @throws Exception 如果流为空或复制过程中发生异常
*/
public static int copyStream(InputStream inputStream, OutputStream outputStream, long maxByteCount)
throws IOException {
if (inputStream == null || outputStream == null) { // 检查流是否为空
throw new IOException("流为空");
}
byte[] buffer = new byte[512]; // 这里512可以视情况调整
int totalSize = 0;
int count;
try (InputStream input = inputStream; OutputStream output = outputStream) { // 使用 try-with-resources 语法来自动关闭流
while ((count = input.read(buffer, 0, buffer.length)) != -1) {
totalSize += count;
if (totalSize > maxByteCount) {
throw new IOException("超过了最大字节数");
}
output.write(buffer, 0, count);
}
}
return totalSize;
}
}
java.io.ByteArrayOutputStream常用方法
write(int b) 写入一个字节。
write(byte[] b) 写入一个字节数组。
write(byte[] b, int off, int len) 写入字节数组的一部分。
toByteArray() 返回包含所有已写入字节的字节数组。
toString() 将字节数组转换为字符串,默认使用平台的默认字符集。
toString(String charsetName) 以指定的字符集将字节数组转换为字符串。
reset() 清空该流,重置计数器,使它可以被重新使用。
close() 由于是内存操作,调用此方法并不会释放系统资源,但可以用来表明流不再使用。
java.io.InputStream#read 方法介绍
read()
1・从输入流中读取下一个字节的数据。返回的是一个介于0到255之间的int值,代表读取到的字节的ASCII值。
2・如果已达到流的末尾,没有更多的数据可读,则返回-1。
read(byte[] b)
1・这个方法从输入流中读取一些字节存储到参数b指向的字节数组中。返回值是实际读取的字节数量。
2・如果没有更多数据可读(即到达流的末尾),则返回-1。
3・如果数组b的长度大于实际可读的字节数,那么只会读取实际可读的字节数量。
read(byte[] b, int off, int len)
1・这个方法从输入流中读取字节到字节数组中,返回值是实际读取的字节数量。
2・如果没有更多数据可读,则返回-1。
3.off: 数组 b 中的起始偏移量,len: 要读取的最大字节数。