文件转换、更换流文件、重新启动服务器时自动删除缓存文件
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class FileUtils {
/**
* MultipartFile 转换成 File
* @param file 要转换的 MultipartFile
* @return 转换后的 File
* @throws Exception 可能抛出的异常
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.isEmpty() || file.getSize() <= 0) {
return null;
}
try (InputStream ins = file.getInputStream()) {
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
toFile.deleteOnExit();
}
return toFile;
}
/**
* 获取流文件
* @param ins 输入流
* @param file 目标文件
*/
private static void inputStreamToFile(InputStream ins, File file) {
try (OutputStream os = new FileOutputStream(file)) {
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除文件
* @param file 要删除的文件
* @return 删除是否成功
*/
public static boolean deleteFile(File file) {
if (file != null && file.exists()) {
return file.delete();
}
return false;
}
/**
* 复制文件
* @param sourceFile 源文件
* @param destFile 目标文件
* @return 复制是否成功
*/
public static boolean copyFile(File sourceFile, File destFile) {
if (!sourceFile.exists()) {
return false;
}
try (InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取文件扩展名
* @param file 文件
* @return 文件扩展名
*/
public static String getFileExtension(File file) {
String fileName = file.getName();
int lastIndex = fileName.lastIndexOf('.');
if (lastIndex != -1 && lastIndex < fileName.length() - 1) {
return fileName.substring(lastIndex + 1);
}
return "";
}
}