问题:java.io.File 对象的方法 delete() 无法删除文件
原因:至少是其中一种原因,有流对象在使用该File对象或者未关闭该流对象
解决 :关闭对应的流
正例:
private String sendReportToNethospital(Endoscopicreport endoscopicreport) throws IOException {
String outerLink = "http://文件的外网链接地址/";
String serverPath = outerLink + endoscopicreport.getReportAddress();
URL url = new URL(serverPath);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
String locationPath = serviceConfig.getLocationPath()+endoscopicreport.getRepotName();
File dir = new File(serviceConfig.getLocationPath());
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(locationPath);
FileOutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(file));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String netHospitalFileInterface = serviceConfig.getNetHospitalFileUrl();
ResponseEntity<String> response = template.postForEntity(netHospitalFileInterface, requestEntity, String.class);
String data = response.getBody();
nethospitalRelationMapper.updateFileIdByCheckno(data,endoscopicreport.getCheckNo());
inputStream.close();
outputStream.close();
new File(locationPath).delete();
return null;
}
如上代码,倒数第3行需要关闭输出流outputStream后, 倒数第2行delete()方法才会到达预期的删除文件的效果。
|