java下载怎么编码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1.设置响应类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            //2,获取输出流
            OutputStream out=response.getOutputStream();
            //获取浏览器
            String browser=request.getHeader("User-Agent");
            //防止乱码IE
            String filename=URLEncoder.encode("学生列表","UTF-8");
            //火狐
            if(browser.toLowerCase().contains("firefox")){
                filename=new String("学生列表".getBytes("UTF-8"),"ISO8859-1");
            }
            //设置附件文件下载的名字
            response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
            //指定的文件
            InputStream is=new FileInputStream("d:/student.xls");
            //缓存字节流
            byte[] buff=new byte[256];
            int len;
            //每一组读取文件的256字节,len长度,后面要截取
            while((len=is.read(buff))!=-1){
                //buff代表每组256,多出来的空白,用截取0-最后一个字
                out.write(buff,0,len);
            }
            //将缓存的字节都强行输出
            out.flush();
            is.close();
    }

 

posted @ 2018-07-23 12:57  J-Joyce  阅读(139)  评论(0编辑  收藏  举报