1.文件工具类方法
public class FileUtils {
/**
* 文件大小转换
* @param String fileSize
*/
public static String fileSizeConvert(String fileSize) {
long fileS = Long.parseLong(fileSize);
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
/**
* @Title: 文件上传
* @MethodName: fileUplodad
* @param file
* @Return boolean
*/
public static boolean fileUplodad(MultipartFile file) {
//文件服务器上文件存放路径(项目的pom文件中配置的上传路径+自定义生成的路径拼接而成)
String pre=new SimpleDateFormat(DATE_FORMAT).format(new Date());
String path = SysConfig.file_savepath + pre; //文件路径,为项目的pom文件中配置的上传路径+自定义生成的路径拼接而成
String fileName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));//存到服务器上的新文件名
File desFilepath = new File(path);
if (!desFilepath.exists()) {
desFilepath.mkdirs();
}
File desFile=new File(path+"/"+newName);
try {
file.transferTo(desFile);
} catch (IOException e) {
log.error("【文件保存】异常,路径:{} ,异常信息:{} ", path, e);
return false;
}
return true;
}
/**
* @Title: 文件下载
* @MethodName: fileDownload
* @param filePath 文件路径(数据库中文件表中存的值,不包含pom文件中配置的上传路径,只是自定义生成的路径和新文件名拼接而成,比如/2021/02/e25ca136-fa52-4269-9751-9f50d82b5814.zip)
* @Return boolean
*/
public HttpServletResponse fileDownload(String filePath, HttpServletResponse response) {
String realPath = SysConfig.file_savepath + filePath;
File file = new File(realPath);
if (file.exists()) {
response.setContentType("application/force-download");//
// response.addHeader(“content-type”, “application/force-download”);
response.addHeader(“Content-Disposition”, “attachment;fileName=” + new String(filePath.substring(filePath.lastIndexOf("/") + 1).getBytes()));// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
ServletOutputStream out = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
out = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
out.write(buffer, 0, i);
i = bis.read(buffer);
}
out.flush();
System.out.println(“文件下载成功”);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return response;
}
/**
* 创建ZIP文件
* @param sourcePath 文件或文件夹路径
* @param zipPath 生成的zip文件存在路径(包括文件名)
*/
public static void createZip(String sourcePath, String zipPath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
//zos.setEncoding("gbk");//此处修改字节码方式。
//createXmlFile(sourcePath,"293.xml");
writeZip(new File(sourcePath), "", zos);
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}
}
}
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if(file.exists()){
if(file.isDirectory()){//处理文件夹
parentPath+=file.getName()+File.separator;
File [] files=file.listFiles();
if(files.length != 0)
{
for(File f:files){
writeZip(f, parentPath, zos);
}
}
else
{ //空目录则创建当前目录
try {
zos.putNextEntry(new ZipEntry(parentPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
FileInputStream fis=null;
try {
fis=new FileInputStream(file);
ZipEntry ze = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(ze);
byte [] content=new byte[1024];
int len;
while((len=fis.read(content))!=-1){
zos.write(content,0,len);
zos.flush();
}
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}finally{
try {
if(fis!=null){
fis.close();
}
}catch(IOException e){
log.error("创建ZIP文件失败",e);
}
}
}
}
}
/**
* zip解压
* @param srcFile zip源文件
* @param destDirPath 解压后的目标文件夹
* @throws RuntimeException 解压失败会抛出运行时异常
*/
public static boolean unZip(File srcFile, String destDirPath) throws RuntimeException {
long start = System.currentTimeMillis();
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解压" + entry.getName());
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保证这个文件的父文件夹必须要存在
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[10240];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解压完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if(zipFile != null){
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
}
2.上一步工具类中获取项目pom文件配置路径的类
@Component
public class SysConfig {
public static String file_savepath;
@Value("${file.file_savepath}")
public void setFile_savepath(String file_savepath) {
SysConfig.file_savepath = file_savepath;
}
}
pom文件配置
注:由于文件工具类方法较多,篇幅较大,具体方法请参考资源文件链接
FileUtil工具类链接
参考:压缩指定文件夹