Java通过指定地址从服务器下载文件到本地

Java通过指定地址从服务器下载文件到本地

万能模板

	try {
			String downloadPath = "*******************************";
            //获取文件名
            String filename = downloadPath.substring(downloadPath.lastIndexOf("\\")+1);
            // 解决中文乱码
           /* filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8");*/

            File file = new File(downloadPath);
            //如果文件不存在
			if(!file.exists()){
			    return;
			}
            //设置响应头,控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            //读取要下载的文件,保存到文件输入流
            in= new FileInputStream(downloadPath);
            //创建输出流
            out= response.getOutputStream();
            //缓存区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区中
            while((len = in.read(buffer)) > 0){
                out.write(buffer, 0, len);
            }
        }finally {
            //关闭
            in.close();
            out.close();
        }

版权声明:本文为Traditional_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。