在创建和使用文件后尝试删除该文件时,java.nio.file.Files.delete(path)方法会抛出java.nio.file.FileSystemException
我的场景如下,我从db中获取一些数据,将其写入一个文件,然后通过inputStrem将该文件提供给客户端响应。 下面是执行此操作的代码:在创建和使用文件后尝试删除该文件时,java.nio.file.Files.delete(path)方法会抛出java.nio.file.FileSystemException,java,spring-boot,Java,Spring Boot,我的场景如下,我从db中获取一些数据,将其写入一个文件,然后通过inputStrem将该文件提供给客户端响应。 下面是执行此操作的代码: public void getErrorsFile(UUID jobId, Pageable pageable, HttpServletResponse response) { List<ValidationErrorsDTO> failedList = getValidationErrors(jobId, pageable); S
public void getErrorsFile(UUID jobId, Pageable pageable, HttpServletResponse response) {
List<ValidationErrorsDTO> failedList = getValidationErrors(jobId, pageable);
String fileName = "failedRows.txt";
PrintWriter writer;
Path path = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
for (ValidationErrorsDTO dto : failedList) {
String line = dto.getLineNumber() + ": " + dto.getValidationMessage() + "\n";
writer.println(line);
}
writer.flush();
path = Paths.get(fileName);
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream inputStream = Files.newInputStream(path)) {
writeStreamToResponse(response, inputStream, fileName);
IOUtils.closeQuietly(inputStream);
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeStreamToResponse(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
response.addHeader("Content-disposition", "attachment;filename=" + fileName);
response.setContentType("txt/plain");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
我为解决该问题所做的SPEP:
如果您有任何有用的建议,我们将不胜感激。您应该以
的方式打开writer实例,并尝试使用类似于打开输入流的资源:
try(writer=newprintwriter(文件名为“UTF-8”)){
对于(ValidationErrorsDTO:failedList){
字符串行=dto.getLineNumber()+“:”+dto.getValidationMessage()+“\n”;
writer.println(行);
}
writer.flush();
path=path.get(文件名);
}捕获(IOE异常){
e、 printStackTrace();
}
看起来您没有关闭Writerwriter.flush();不是吗?是的,这绝对是问题所在,非常感谢。
java.nio.file.FileSystemException: failedRows.txt: The process cannot access the file because it is being used by another process.