Java工具类(20)—文件 上传工具类
package com.awifi.capacity.docker.manager.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Slf4j
public class FileUtil {
public static String getFileContent(String path){
StringBuilder sb = new StringBuilder();
BufferedReader br=null;
try {
InputStream inputStream = new ClassPathResource(path).getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
String string = null;
while ((string = br.readLine()) != null){
sb.append(string+"\n");
}
br.close();
} catch(Exception e){
log.error("系统找不到指定文件,请核对文件存放地址");
throw new RuntimeException("系统找不到指定文件,请核对文件存放地址");
}finally {
if(null != br){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static Object saveFile(MultipartFile file, String path) {
if (file.isEmpty()) {
return "未选择文件";
}
String filename = file.getOriginalFilename();
File temp = new File(path);
if (!temp.exists()) {
temp.mkdirs();
}
File localFile = new File(path + filename);
try {
file.transferTo(localFile);
log.info("{} 上传成功", file.getOriginalFilename());
} catch (IOException e) {
log.error("上传失败,{}", e.getMessage());
return "上传失败";
}
return localFile.getPath();
}
public static void main(String[] args){
}
}