字节是二进制数据的单位,1字节(Byte)=8位(bit),byte数组一般用来处理文件流的操作
InputStream is = new FileInputStream(new File("D://a.txt"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int temp;
while ((temp = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, temp);
}
//转换后的byte[]
byte[] finalBytes = outputStream.toByteArray();
二、通过IOUtils
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
InputStream inputStream = obsObject.getObjectContent();
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
return bytes;
这种方式更加快速 位于的包:package org.apache.commons.compress.utils;
文件下载
InputStream input = obsObject.getObjectContent();
// 读取对象内容
byte[] b = new byte[1024];
OutputStream bos = response.getOutputStream();
int len;
while ((len = input.read(b)) != -1) {
bos.write(b, 0, len);
}
二、如下载excel文件中包含图片
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
startColumn, startRow, startColumn + column + 1, startRow + row + 1);
drawing.createPicture(anchor, wb.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_PNG));
这里的createPicture方法传递过来的bytes就是文件的byte数组
byte[] bytes = DatatypeConverter.parseBase64Binary("base64字符串");
DatatypeConverter位于package javax.xml.bind包下
String base64Str = DatatypeConverter.printBase64Binary(bytes);
String str = new String(Base64.encode(baos.toByteArray()));
为什么文件的读写通常用byte数组来接收? 为什么很多数据都要转换成BYTE[]类型的数组?为什么不用BIT[]?