闲话不多说直接上代码
Controller
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(@ModelAttribute("glpLanguageFileDTO")GLPLanguageFileDTO glpLanguageFileDTO,HttpServletResponse response) throws GLPBusinessException, IOException {
//设置文件名字(可自由发挥)
String name=glpLanguageFileDTO.getLanguageFileType().toLowerCase()+"_"+glpLanguageFileDTO.getLanguageIsoCode()+".properties";
//若需要生成临时文件可指定路径,则FileOutputStream(name)和FileInputStream(name)中的"name"替换成"path"
//String path="\\\\VATPDDSCH-02\\FileServer\\Registration\\TOC_GSO\\"+name;
response.setContentType("multipart/form-data");
//为properties添加注释
response.setHeader("Content-Disposition", "attachment;fileName="+name);
ServletOutputStream out;
//从数据库中查出相关的数据到Properties 类中
Properties prop = glpLanguageService.downloadStandardFile(glpLanguageFileDTO);
//保存文件
FileOutputStream outputStream = new FileOutputStream(name);
prop.store(outputStream, name);
outputStream.close();
//读取文件
FileInputStream inputStream = new FileInputStream(name);
out = response.getOutputStream();
int b = 0;
byte[] buffer=new byte[inputStream.available()];
while ((b=inputStream.read(buffer))!=-1){
//写到输出流(out)中
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();
}
GLPLanguageService类
生成Properties,(可根据自己需要的文件进行编写)此处我用的事Properties文件
private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
@Override
public Properties downloadStandardFile(GLPLanguageFileDTO glpLanguageFileDTO)
throws GLPBusinessException {
Properties props = new Properties();
try {
GLPLanguageFile glpLanguages=glpLanguageDao.getGLPLanguageFileByTypeAndIso(glpLanguageFileDTO.getLanguageFileType(), glpLanguageFileDTO.getLanguageIsoCode()).get(0);
InputStream is =new ByteArrayInputStream(glpLanguages.getLanguageContent());
propertiesPersister.load(props, is);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}