java通用的下载方式

java通用的下载方式就是读流的方式:就是将文件转换成java流然后将流在进行转化为文件

代码如下:

      request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 获取文件路径
            String filePath = request.getParameter("fileUrl");
            // 创建文件对象
            File file = new File(filePath);
            // 获取文件名
            String fileName = new String(file.getName().getBytes("ISO-8859-1"), "utf-8");
            //以流的形式下载文件
            BufferedInputStream bis =
                    new BufferedInputStream(new FileInputStream(file));
            String fileDownloadUrl = "E:\\Code\\ideaCode\\educational\\src\\main\\webapp\\resource\\downloadFile\\";
//            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//            fileDownloadUrl = fileDownloadUrl + fileName + fileSuffix;
            fileDownloadUrl = fileDownloadUrl + fileName;
            // 输出文件
            BufferedOutputStream out =
                    new BufferedOutputStream(
                            new FileOutputStream(fileDownloadUrl));
            // 读取文件一次读取多少字节
            byte[] bytes = new byte[2048];
            int n = -1;
            // 循环读取
            while ((n = bis.read(bytes, 0, bytes.length)) != -1) {
                //转换成字符串
                String str = new String(bytes, 0, n, "UTF-8");
                System.out.println(str);
                //写入相关文件
                out.write(bytes, 0, n);
            }
            //清除缓存
            out.flush();
            //关闭流
            bis.close();
            out.close();

猜你喜欢

转载自blog.csdn.net/h_j_c_123/article/details/91411536