Java将文件输入流导出到本地

62 阅读1分钟

最近给工作中写的IO流相关,由于太长时间没用IO流,有点不熟练了,写个帖子记录下来自己写的代码,方便以后查阅。

public void fileUpload(HttpServletRequest request) throws Exception {  
   
String servletPath = request.getServletPath();  
//得到文件名  
int lastIndexOf = servletPath.lastIndexOf("/");  
String fileName = servletPath.substring(lastIndexOf + 1);  
//得到文件输入流  
ServletInputStream fileInputStream = request.getInputStream();  
  
//将文件保存到本地  
  
//文件路径  
String filePath = XinConfig.getProfile();  
LocalDate currDate = LocalDate.now();  
filePath = filePath+currDate.format(DateTimeFormatter.ofPattern("/yyyy/MM/dd/"));  
  
File tempPath = new File(filePath);  
if (!tempPath.exists()) {  
tempPath.mkdirs();  
}  
filePath = filePath + fileName;  
  
int bytesRead = 0;  
byte[] buffer = new byte[10 * 1024 * 1024];  
//使用输出流输出输入流的字节  
FileOutputStream outputStream = null;  
  
try {  
outputStream = new FileOutputStream(filePath);  
while ((bytesRead = fileInputStream.read(buffer, 0, 8192)) != -1) {  
outputStream.write(buffer, 0, bytesRead);  
}  
fileInputStream.close();  
} catch (IOException e) {  
log.error("Stream copy exception", e);  
throw new IllegalArgumentException("文件上传失败");  
} finally {  
if (outputStream != null) {  
try {  
outputStream.close();  
} catch (IOException e) {  
log.error("Stream close exception", e);  
  
}  
}  
if (fileInputStream != null) {  
try {  
fileInputStream.close();  
} catch (IOException e) {  
log.error("Stream close exception", e);  
}  
}  
}  
  
  
}