在网页使用缓冲流BufferedInputStream和BufferedOutputStream上传下载

缓冲流出来这么久,网上没看到有几个使用的

我自己写了俩方法,一个下载,一个上传,速度都很快

上传的

public void upload(MultipartFile excelFile) {
        String fileName = excelFile.getOriginalFilename();
        BufferedInputStream bi=null;
        BufferedOutputStream bo = null;
        File file = new File("保存文件夹" + fileName);
        try {
            bi = new BufferedInputStream(excelFile.getInputStream());
            bo = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buffer = new byte[1024 * 8];
            int byteread = 0;
            while ((byteread = bi.read(buffer)) != -1) {
                bo.write(buffer, 0, byteread);
            }
            bo.flush();
            bo.close();
            bi.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bi != null) {
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bo != null) {
                try {
                    bo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

下载的

public void download(HttpServletResponse response) {
        String fileName = "文件";
        BufferedInputStream bi = null;
        BufferedOutputStream bo = null;
        try {
            bi = new BufferedInputStream(new FileInputStream(new File(fileName)));
            bo = new BufferedOutputStream(response.getOutputStream());

            response.setContentType("application/json;charset=gb2312");
            response.setHeader("Content-Disposition", "attachment;filename=qosApiInfo.log");

            int len = 0;
            byte[] b = new byte[1024 * 8];
            while ((len = bi.read(b)) != -1) {
                bo.write(b, 0, len);
            }
            bo.flush();
            bo.close();
            bi.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bi != null) {
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bo != null) {
                try {
                    bo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

你可能感兴趣的:(自己实现的小玩意儿)