如何使⽤ByteArrayOutputStream下载⽂件
⽬录
使⽤ByteArrayOutputStream下载⽂件
使⽤POI导出数据,然后将其下载
使⽤ByteArrayOutputStream解决IO乱码
说下经过
⼩结⼀下
使⽤ByteArrayOutputStream下载⽂件
//⽂件名称
String filepath = ServletContext()
.QrCodeUrl());
File file = new File(filepath);
String fileName = new Date().getTime()+".png";
//设置请求信息
HttpServletResponse response = Response();
response.ContentType());
response.setHeader("Content-disposition",
"attachment; filename="+fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
FileInputStream inputStream = new FileInputStream(file);
byte [] buffer  = new byte[3];
while((len = ad(buffer)) != -1)
{
baos.write(buffer, 0,  len);
}
byte[] bytes = ByteArray();
response.setHeader("Content-Length", String.valueOf(bytes.length));
BufferedOutputStream bos = null;
bos = new OutputStream());
bos.write(bytes);
bos.close();
baos.close();
使⽤POI导出数据,然后将其下载
//此处将HSSFWorkbook wb处理好,然后最后要导出⽂件时加上此代码。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.ContentType());
response.setHeader("Content-disposition",
"attachment; filename=monthPayment.xls");
wb.write(baos);
byte[] bytes = ByteArray();
response.setHeader("Content-Length", String.valueOf(bytes.length));
BufferedOutputStream bos = null;
bos = new OutputStream());
bos.write(bytes);
bos.close();
baos.close();
1、使⽤ad(buffer)⽅法分段的把txt⽂本中的内容写⼊buffer数组。
这⾥为buffer数组指定了长度为3,所以“hello world!”这组长度为11的数据会被分成4次写⼊到buffer数组中。
当ad(buffer)把数据都写⼊到buffer数组之后,它最后还会返回⼀次len为-1的值,代表数据完全读完。
2、使⽤outStream.write(buffer, 0, len)⽅法,在while循环体内把每次写⼊到buffer数组的值再次叠加写⼊到内存缓冲区中。
3、使⽤ByteArray()⽅法把内存缓冲区中的数据流转换成字节数组。
4、最后把字符数组转换成字符串进⾏返回return new String(data)。
使⽤ByteArrayOutputStream解决IO乱码
说下经过
今天在⽤s3接⼝做ceph储存的时候,要实现⼀个io下载的接⼝。
需要把InputStream转成byte[],⼀开始,是的写法是这样的:
byte[] buf = new byte[(int) fileSize];
InputStream in = ObjectContent();
jdk怎么使用
try {
for (int n = 0; n != -1; ) {
n = in.read(buf, 0, buf.length);
}
} catch (IOException e) {
<(e.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
<(e.getMessage());
}
}
可是下载的⽂件稍⼤⼀些,就会出现乱码。
于是换了⽹上推荐的,使⽤byte缓存的⽅法,来实现InputStream转成byte[]:
private static byte[] inputToByte(InputStream inStream, int fileSize) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[fileSize];
int rc;
while ((rc = ad(buff, 0, fileSize)) > 0) {
swapStream.write(buff, 0, rc);
}
ByteArray();
}
乱码的情况就解决了!
⼩结⼀下
IO这块不是很熟悉,尽量不要⽤原⽣的⽅法去写,⽽应该使⽤JDK封装好的⽅法去实现。避免出现⼀些意料之外的问题。PS:⾄于上⾯那段代码为什么会出现乱码,暂时还未研究出来。
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。