導出word,以下為導出單個和zip的兩種格式。 CountDownLatch運用 CountDownLatch和ExecutorService 線程池cachedThreadPool.submit 1、CountDownLatch 概念 CountDownLatch可以使一個獲多個線程等待其他線程 ...
導出word,以下為導出單個和zip的兩種格式。
CountDownLatch運用
CountDownLatch和ExecutorService 線程池cachedThreadPool.submit
1、CountDownLatch 概念
CountDownLatch可以使一個獲多個線程等待其他線程各自執行完畢後再執行。
CountDownLatch 定義了一個計數器,和一個阻塞隊列, 當計數器的值遞減為0之前,阻塞隊列裡面的線程處於掛起狀態,當計數器遞減到0時會喚醒阻塞隊列所有線程,這裡的計數器是一個標誌,可以表示一個任務一個線程,也可以表示一個倒計時器,
CountDownLatch可以解決那些一個或者多個線程在執行之前必須依賴於某些必要的前提業務先執行的場景。
點擊查看代碼
@Override
public void batchExportWord(PreDefenceApplyDto preDefenceApplyDto) {
SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
if (loginUser == null || StringUtils.isBlank(loginUser.getUserId())) {
throw new ServiceException(SimpleErrorCode.UserNotLogin);
}
if(StringUtils.isBlank(preDefenceApplyDto.getGrade())){
throw new ServiceException(301,"請選擇年級");
}
String grade = preDefenceApplyDto.getGrade();
List<String> collegeIds = preDefenceApplyDto.getCollegeIds();
String majorId = preDefenceApplyDto.getMajorId();
// 查詢學生論文結果
List<String> studentIds = preDefenceApplyMapper.selectHasResStu(grade,collegeIds,majorId);
if(CollectionUtils.isEmpty(studentIds)){
throw new ServiceException(302,"暫無審核通過的學生可導出");
}
//學校名稱
String schoolName = publicMapper.querySchoolName();
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
String downloadName = "情況表.zip";
response.setContentType("application/zip;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
String realPath = request.getSession().getServletContext().getRealPath("");
try (
OutputStream outputStream = response.getOutputStream();
// 壓縮流
ZipOutputStream zos = new ZipOutputStream(outputStream)){
ExecutorService cachedThreadPool = Executors.newFixedThreadPool(studentIds.size());
CountDownLatch latch = new CountDownLatch(studentIds.size());
for(String stuId : studentIds){
cachedThreadPool.submit(() -> {
try {
zipPreWord( bufferedInputStream, zos,
stuId, schoolName ,realPath);
} catch (IOException e) {
e.printStackTrace();
}
latch.countDown();
});
}
cachedThreadPool.shutdown();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void zipPreWord( BufferedInputStream bufferedInputStream,ZipOutputStream zos,
String studentId,String schoolName ,String realPath) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);
String fileName =studentId+preDefenceApplyVo.getStudentName();
fileName=fileName.replaceAll("/", "-")+"情況表.doc";
String filePath = realPath + File.separator + fileName;
File outFile = new File(filePath );
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
Template template = null;
try {
template = configuration.getTemplate(schoolName + "情況表2.ftl");
} catch (IOException e) {
log.error("context", e);
throw new ServiceException(SimpleErrorCode.ExecFailure);
}
Map<String, Object> params = new HashMap<>();
params.put("preDefenceApplyVo", preDefenceApplyVo);
params.put("schoolName", schoolName);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
template.process(params, out);
} catch (TemplateException e) {
e.printStackTrace();
}
ZipEntry zipEntry = new ZipEntry(fileName);
bufferedInputStream = new BufferedInputStream( new FileInputStream(outFile));
zos.putNextEntry(zipEntry);
while ((len = bufferedInputStream.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
}
@Override
public void exportWord(PreDefenceApplyDto preDefenceApplyDto) {
SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
if (loginUser == null) {
throw new ServiceException(SimpleErrorCode.UserNotLogin);
}
String studentId = loginUser.getUserId();
if (preDefenceApplyDto != null && StringUtils.isNotBlank(preDefenceApplyDto.getStudentId())) {
studentId = preDefenceApplyDto.getStudentId();
}
//學校名稱
String schoolName = publicMapper.querySchoolName();
PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);
String fileName = schoolName + "情況表.doc";
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + stringToUnicode(fileName));
String filePath = request.getSession().getServletContext().getRealPath("/");
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
Template template = null;
try {
template = configuration.getTemplate(schoolName + "情況表2.ftl");
} catch (IOException e) {
log.error("context", e);
throw new ServiceException(SimpleErrorCode.ExecFailure);
}
Map<String, Object> params = new HashMap<>();
params.put("preDefenceApplyVo", preDefenceApplyVo);
params.put("schoolName", schoolName);
File outFile = new File(filePath + "/" + fileName);
byte[] buffer = new byte[1024];
int len = 0;
BufferedInputStream bufferedInputStream = null;
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
try {
template.process(params, out);
} catch (TemplateException e) {
e.printStackTrace();
}
FileInputStream fileInputStream = new FileInputStream(outFile);
bufferedInputStream = new BufferedInputStream(fileInputStream);
while ((len = bufferedInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
out.close();
fileInputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (outFile.exists()) {
if (!outFile.delete()) {
log.info("刪除失敗!");
}
}
}
}