JavaEE——将访问的内容按照指定格式文件下载下来

时间:2021-06-23 20:58:49
 (1)如下代码是在Controller里面,当发送HttpServletRequest 请求之后,将服务器返回的HttpServletResponse响应内容下载下来
@ResponseBody
@RequestMapping(value = "getDown.do",method = RequestMethod.GET)
public String getDown(ModelMap map,@RequestParam int shipMmsi,@RequestParam int startTime,@RequestParam int endTime,HttpServletRequest request,
HttpServletResponse response) throws Exception {
//设置编码
response.setCharacterEncoding("utf-8");

//setContentType为文件上传下载重要属性设置方法,详细可查看链接:http://blog.sina.com.cn/s/blog_a03d702f010143tw.html
//http://zhangjunhd.blog.51cto.com/113473/19631

response.setContentType("multipart/form-data");

String fileName = "ship_" + shipMmsi + "_start_" + startTime + "_end_" + endTime+".txt";
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);

String fileContent = listOneShipHistory_chinese(shipMmsi, startTime, endTime);//

String filePath="download";

//写文件
FileUtils file=new FileUtils(fileName,filePath);
file.saveFile2(fileContent);

//下载文件
if(file.down(request,response)){
System.out.println("success");
}else{
System.out.println("fail");
}
return null;
}



(2)获取数据内容并格式化  
public String listOneShipHistory_chinese(int shipMmsi,int startTime,int endTime){
List<ShipHistoryPosition> list= oneShipPosService.oneShipHistoryPositions(shipMmsi, startTime, endTime);//调用后端接口获取数据
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 换行符
String n="\r\n";
String f=",";
String msiInfo="";

if(list.size()==0){
msiInfo="目标编号:"+shipMmsi+"在"+dateFormat.format((long)startTime*1000)+"至"+dateFormat.format((long)endTime*1000)+"时间范围内无数据";
return msiInfo;
}

//将筛选的数据格式化并返回
msiInfo+="目标编号:"+shipMmsi+n;
msiInfo+="时间范围:"+dateFormat.format((long)startTime*1000)+"至"+dateFormat.format((long)endTime*1000)+n;
msiInfo+="位置信息:"+n;

for(ShipHistoryPosition position:list){
msiInfo+="经度:"+position.getLongitude()/600000+f;
msiInfo+="纬度:"+position.getLatitude()/600000+f;
msiInfo+="船艏向:"+position.getHeading()+f;

Long time= (long) position.getTime()*1000;
msiInfo+="时间:"+dateFormat.format(time)+n;
}

return msiInfo;
}


(3)文件读写操作工具类,包含上面调用的两个方法
 
package com.ict.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
public String fileRoad;
public String fileName;
public String filePath;

public FileUtils(String fileName, String filePath){
this.fileName=fileName;
this.filePath=filePath;
this.fileRoad=getFileRoad()+filePath;
}

public FileUtils(){};

// 逐行读取文件加入list
public List<String> getFileContent(String filePath) throws Exception{
List<String> list=new ArrayList<>();

FileReader fr = new FileReader(filePath);
BufferedReader bufferedreader = new BufferedReader(fr);
String instring;
while ((instring = bufferedreader.readLine())!= null) {
list.add(instring);
}
fr.close();

return list;
}

public void saveFile(String content){
String fileRoad=this.fileRoad+"/"+this.fileName;
System.out.println(fileRoad);

FileWriter writer;
try {
writer = new FileWriter(fileRoad,true);//有true参数则追加写
writer.write(content);
writer.write("\r\n");

writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void saveFile2(String content){
String fileRoad=this.fileRoad+"/"+this.fileName;
System.out.println(fileRoad);

FileWriter writer;
try {
writer = new FileWriter(fileRoad);//无true参数则覆盖写
writer.write(content);
writer.write("\r\n");

writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

//获取项目所在路径
public String getFileRoad(){
String path1 = Thread.currentThread()
.getContextClassLoader().getResource("").getPath();
return path1;
}

public boolean down( HttpServletRequest request,
HttpServletResponse response){
try {
String path1 = getFileRoad()
+ filePath + "/" + fileName;
System.out.println(path1);
InputStream inputStream = new FileInputStream(path1);

OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}