java springMVC数据的打包下载
2017-01-09 11:12
387 查看
前几天做了一个上传下载功能,开始下载做的很顺利,然而上传的时候遇到很多难题,好在都已经解决。
虽然这个下载功能做完了,但我还不是很满意,因为我创建文件与压缩包都是在服务器磁盘中操作的,原本想直接在内存中操作,
但查了半天,还是不知道该怎么做,如果有看到这个文章并正好知道的朋友麻烦告诉或指正一下。
好了,上代码:
//1、获取数据,根据数据(树形)创建目录与目录下的文件夹。
//2、说明文件在指定目录下创建(xml文件,说明导出文件结构与各结构文件名称)
/**
* 创建xml文件
* @param path
* 创建xml文件路径
* @param template
* 文件内容
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void createXML(File xmlFile,List<Map<String,Object>> template,Element parentRoot) throws IOException{
if(parentRoot ==null){
parentRoot = DocumentHelper.createElement("root");
}
for(Map<String, Object> chilids : template){
Iterator entries = chilids.entrySet().iterator();
if(chilids.get("id")!=null && chilids.get("type")!=null){
Element element = parentRoot.addElement("id");
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
if(entry.getKey().equals("childs")){
List<Map<String,Object>> chilidMap = (List<Map<String, Object>>) chilids.get("childs");
if(chilidMap!=null && chilidMap.size()>0){
Element element1 = element.addElement("childs");
createXML(xmlFile,chilidMap,element1);
}
}else{
element.addElement(entry.getKey()+"").addText(entry.getValue()==null?"":entry.getValue()+"");
}
}
}else{
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
parentRoot.addElement(entry.getKey()+"").addText(entry.getValue()+"");
}
}
}
//把生成的xml文档存放在硬盘上
OutputFormat format = new OutputFormat();
// format.setNewlines(true); //是否换行
format.setEncoding("UTF-8");//设置编码格式
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile),format);
xmlWriter.write(parentRoot);
xmlWriter.close();
}
//3、复制所用到的jar包到指定目录
/**
* 将源文件复制到目标文件中
* @param jarPath
* 源文件路径
* @param sourcePath
* 目标文件路径
*/
@SuppressWarnings("unused")
public void copyFile(String sourcePath, String destPath) {
int bytesum = 0;
int byteread = 0;
InputStream inStream = null;
FileOutputStream fs = null;
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
if(!destFile.exists()){
try {
destFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try{
//FileUtils.copyDirectory(sourceFile, to);
if (sourceFile.exists()) { //文件存在时
inStream = new FileInputStream(sourcePath); //读入原文件
fs = new FileOutputStream(destFile);
byte[] buffer = new byte[1444];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(inStream != null){
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fs != null){
try {
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//4、压缩文件
/**
* @decription 将源目录下的文件压缩到指定压缩文件中
* @param resourcesPath
* @param targetPath
* @throws IOException
* @throws Exception
*/
public static synchronized void compressedFile(String sourcesPath,String exportPath,String exportFileName) throws IOException{
File sourcesFile = new File(sourcesPath); //源文件
File targetFile = new File(exportPath); //目的
//如果目的路径不存在,则新建
if(!targetFile.exists()){
targetFile.mkdirs();
}
File exportFile = new File(exportPath+separator+exportFileName); //目的
//如果目的路径不存在,则新建
if(!exportFile.exists()){
exportFile.createNewFile();
}
FileOutputStream outputStream =null;
ZipOutputStream out = null;
try {
outputStream = new FileOutputStream(exportFile);
out = new ZipOutputStream(outputStream);
out.setEncoding("UTF-8");
createCompressedFile(out, sourcesFile, "");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream !=null){
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.gc();
}
/**
* @decription 生成压缩文件。
* 如果是文件夹,则使用递归,进行文件遍历、压缩
* 如果是文件,直接压缩
* @param out 输出流
* @param file 目标文件
* @param dir 文件名称
* @throws Exception
*/
public static void createCompressedFile(ZipOutputStream out,File file,String dir){
//如果当前的是文件夹,则进行进一步处理
if(file.isDirectory()){
//得到文件列表信息
File[] files = file.listFiles();
//将文件夹添加到下一级打包目录
try {
out.putNextEntry(new ZipEntry(dir+separator));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dir = dir.length() == 0 ? "" : dir +separator;
//循环将文件夹中的文件打包
for(int i = 0 ; i < files.length ; i++){
createCompressedFile(out, files[i], dir + files[i].getName()); //递归处理
}
}else{ //当前的是文件,打包处理
//文件输入流
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
//进行写操作
int j = 0;
byte[] buffer = new byte[1024];
while((j = fis.read(buffer)) > 0){
out.write(buffer,0,j);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//5、下载
OutputStream os = null;
FileInputStream in = null;
try {
File zipFile = new File(exportFilePath+separator+exportFileName);
response.setContentType("application/octet-stream");
String zipName = URLEncoder.encode(zipFile.getName(), "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="
+ zipName);
os = response.getOutputStream();
in = new FileInputStream(zipFile);
IOUtils.copy(in, os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//导出后删除打包文件所在文件夹
FileUtils.deleteDirectory(exportFilePath);
}
虽然这个下载功能做完了,但我还不是很满意,因为我创建文件与压缩包都是在服务器磁盘中操作的,原本想直接在内存中操作,
但查了半天,还是不知道该怎么做,如果有看到这个文章并正好知道的朋友麻烦告诉或指正一下。
好了,上代码:
//1、获取数据,根据数据(树形)创建目录与目录下的文件夹。
//2、说明文件在指定目录下创建(xml文件,说明导出文件结构与各结构文件名称)
/**
* 创建xml文件
* @param path
* 创建xml文件路径
* @param template
* 文件内容
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void createXML(File xmlFile,List<Map<String,Object>> template,Element parentRoot) throws IOException{
if(parentRoot ==null){
parentRoot = DocumentHelper.createElement("root");
}
for(Map<String, Object> chilids : template){
Iterator entries = chilids.entrySet().iterator();
if(chilids.get("id")!=null && chilids.get("type")!=null){
Element element = parentRoot.addElement("id");
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
if(entry.getKey().equals("childs")){
List<Map<String,Object>> chilidMap = (List<Map<String, Object>>) chilids.get("childs");
if(chilidMap!=null && chilidMap.size()>0){
Element element1 = element.addElement("childs");
createXML(xmlFile,chilidMap,element1);
}
}else{
element.addElement(entry.getKey()+"").addText(entry.getValue()==null?"":entry.getValue()+"");
}
}
}else{
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
parentRoot.addElement(entry.getKey()+"").addText(entry.getValue()+"");
}
}
}
//把生成的xml文档存放在硬盘上
OutputFormat format = new OutputFormat();
// format.setNewlines(true); //是否换行
format.setEncoding("UTF-8");//设置编码格式
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile),format);
xmlWriter.write(parentRoot);
xmlWriter.close();
}
//3、复制所用到的jar包到指定目录
/**
* 将源文件复制到目标文件中
* @param jarPath
* 源文件路径
* @param sourcePath
* 目标文件路径
*/
@SuppressWarnings("unused")
public void copyFile(String sourcePath, String destPath) {
int bytesum = 0;
int byteread = 0;
InputStream inStream = null;
FileOutputStream fs = null;
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
if(!destFile.exists()){
try {
destFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try{
//FileUtils.copyDirectory(sourceFile, to);
if (sourceFile.exists()) { //文件存在时
inStream = new FileInputStream(sourcePath); //读入原文件
fs = new FileOutputStream(destFile);
byte[] buffer = new byte[1444];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(inStream != null){
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fs != null){
try {
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//4、压缩文件
/**
* @decription 将源目录下的文件压缩到指定压缩文件中
* @param resourcesPath
* @param targetPath
* @throws IOException
* @throws Exception
*/
public static synchronized void compressedFile(String sourcesPath,String exportPath,String exportFileName) throws IOException{
File sourcesFile = new File(sourcesPath); //源文件
File targetFile = new File(exportPath); //目的
//如果目的路径不存在,则新建
if(!targetFile.exists()){
targetFile.mkdirs();
}
File exportFile = new File(exportPath+separator+exportFileName); //目的
//如果目的路径不存在,则新建
if(!exportFile.exists()){
exportFile.createNewFile();
}
FileOutputStream outputStream =null;
ZipOutputStream out = null;
try {
outputStream = new FileOutputStream(exportFile);
out = new ZipOutputStream(outputStream);
out.setEncoding("UTF-8");
createCompressedFile(out, sourcesFile, "");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream !=null){
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.gc();
}
/**
* @decription 生成压缩文件。
* 如果是文件夹,则使用递归,进行文件遍历、压缩
* 如果是文件,直接压缩
* @param out 输出流
* @param file 目标文件
* @param dir 文件名称
* @throws Exception
*/
public static void createCompressedFile(ZipOutputStream out,File file,String dir){
//如果当前的是文件夹,则进行进一步处理
if(file.isDirectory()){
//得到文件列表信息
File[] files = file.listFiles();
//将文件夹添加到下一级打包目录
try {
out.putNextEntry(new ZipEntry(dir+separator));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dir = dir.length() == 0 ? "" : dir +separator;
//循环将文件夹中的文件打包
for(int i = 0 ; i < files.length ; i++){
createCompressedFile(out, files[i], dir + files[i].getName()); //递归处理
}
}else{ //当前的是文件,打包处理
//文件输入流
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
//进行写操作
int j = 0;
byte[] buffer = new byte[1024];
while((j = fis.read(buffer)) > 0){
out.write(buffer,0,j);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//5、下载
OutputStream os = null;
FileInputStream in = null;
try {
File zipFile = new File(exportFilePath+separator+exportFileName);
response.setContentType("application/octet-stream");
String zipName = URLEncoder.encode(zipFile.getName(), "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="
+ zipName);
os = response.getOutputStream();
in = new FileInputStream(zipFile);
IOUtils.copy(in, os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//导出后删除打包文件所在文件夹
FileUtils.deleteDirectory(exportFilePath);
}
相关文章推荐
- spring mvc @responsebody返回json数据 ie浏览器弹出下载页面 解决方案
- spring java xml 多文件打包下载
- JAVA Spring web mvc 学习 之 6:数据验证
- 手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)
- 【SSM框架 SSM项目源码 SSM源码 下载】java框架整合Springmvc+mybatis+shiro+bootstrap
- .NET/ASP.NET/C#/WCF/SQL Server/My SQL/Java/JSP/JDBC/Spring/Spring MVC/PHP/Python/Ruby/Shell/Agile/CSS/HTML/HTTP/Unix/Linux大量PDF书籍/电子书籍下载, Effective Java 下载
- 手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)
- SpringMVC+Maven开发最小“自然语言理解”项目攻略(附源码打包下载及详细说明)
- 手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)
- java web SpringMVC后端传json数据到前端页面实例代码
- java web SpringMVC后端传json数据到前端页面
- Java 批量生成二维码图片,并打包成可直接下载的zip包(spring boot)
- java springmvc 数据调用 highcharts
- 手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)
- java学习笔记(二)springMVC +mybatis 取数据流程
- Java Web SpringMVC AJAX,实现页面懒加载数据
- java springmvc + mybatis 批量导出excel数据到mysql
- JAVA Spring web mvc 学习 之 6:数据类型转换 -格式转换
- java SpringMVC + Mybatis 一套前台到后台完整获取数据的步骤
- java spring mvc完整包下载地址