0
点赞
收藏
分享

微信扫一扫

Java 字节流的使用

滚过红尘说红尘 2022-02-17 阅读 75

使用流的时候,一般有两种情况.

(1) 会产生临时文件 , 如FileOutputStream、FileIutputStream 此类需要在磁盘产生文件
(2) 不产生临时文件,可以使用字节流如ByteArrayOutputStream、ByteArrayInputStream 等流,需要将 输入流 和 输出流 互相转化。
外部链接

	// 产生临时文件,需手动删除文件
	FileOutputStream fos = null;
	String path = "D:\\my_work_space\\output.xls";
	try {
	    fos = new FileOutputStream(path);
	    workbook.write(fos);
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    try {
	        assert fos != null;
	        fos.flush();
	        fos.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	//删除文件
	File file = new File(path);
	file.delete();
	// 不产生临时文件
	// 获取当前线程上下文中的响应
    HttpServletResponse resp = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    //POI 将表格写入输出流
    HSSFWorkbook workbook = new HSSFWorkbook();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        workbook.write(baos);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	// 输出流 转为 输入流 【重点】
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    try {
        assert resp != null;
        int b;
        while ((b= bais.read()) != -1){
        	//将excel的字节输入流,写入响应是输出流中
            resp.getOutputStream().write(length);
        }
        //resp.getOutputStream().print("create excel success !");
    } catch (IOException e) {
        e.printStackTrace();
    }
举报

相关推荐

0 条评论