package com.farriver.bwf.common.utilities; import com.farriver.bwf.common.model.UploadTemplateData; import com.google.common.io.Files; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; public class FileUtil { public static String writeFile(String uploadPath, MultipartFile file) throws IOException { String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String pathcategory = ""; switch (fileExt.toUpperCase()) { case "DOC": case "DOCX": case "TXT": case "XSL": case "XSLX": case "XLS": case "XLSX": case "PPT": case "PDF": pathcategory = "/document/"; break; case "PNG": case "JPEG": case "JPG": case "ICO": case "GIT": pathcategory = "/picture/"; break; default: pathcategory = "/others/"; break; } String relativepath = pathcategory; String diskPath = uploadPath + relativepath; FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return relativeFilePath; } public static UploadTemplateData writeDocumentFile(String module, String uploadPath, MultipartFile file) throws IOException { var result = new UploadTemplateData(); String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String relativepath = String.format("/%s/template/export/%s/", "bwf", module); String diskPath = String.format("%s%s", uploadPath, relativepath); FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; result.setRelativepath(relativeFilePath); result.setAbsolutepath(fileUrl); } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return result; } public static UploadTemplateData writeExportTemplateFile(String module, String uploadPath, MultipartFile file) throws IOException { var result = new UploadTemplateData(); String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String relativepath = String.format("/%s/template/export/%s/", "bwf", module); String diskPath = String.format("%s%s", uploadPath, relativepath); FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; result.setRelativepath(relativeFilePath); result.setAbsolutepath(fileUrl); } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return result; } public static UploadTemplateData writeImportTemplateFile(String module, String uploadPath, MultipartFile file) throws IOException { var result = new UploadTemplateData(); String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String relativepath = String.format("/%s/template/import/%s/", "bwf", module); String diskPath = String.format("%s%s", uploadPath, relativepath); FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; result.setRelativepath(relativeFilePath); result.setAbsolutepath(fileUrl); } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return result; } public static UploadTemplateData writeBOLFile(String module, String uploadPath, MultipartFile file) throws IOException { var result = new UploadTemplateData(); String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String relativepath = String.format("/%s/bol/%s/", "bwf", module); String diskPath = String.format("%s%s", uploadPath, relativepath); FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; result.setRelativepath(relativeFilePath); result.setAbsolutepath(fileUrl); } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return result; } public static UploadTemplateData writeReportFile(String module, String uploadPath, MultipartFile file) throws IOException { var result = new UploadTemplateData(); String relativeFilePath = null; InputStream inputStream = null; OutputStream outputStream = null; try { Date date = new Date(); String fileUrl = null; String filename = file.getOriginalFilename(); String fileShortName = getShortNameName(filename, '.'); String fileExt = getExtName(filename, '.'); String newfilename = String.format("%s-%s.%s", fileShortName, DateTimeUtils.dateToString(date, "yyyyMMddhhmmss"), fileExt); String relativepath = String.format("/%s/report/%s/", "bwf", module); String diskPath = String.format("%s%s", uploadPath, relativepath); FileUtil.mkdir(diskPath); if (diskPath.endsWith("\\") || diskPath.endsWith("/")) fileUrl = diskPath + newfilename; else fileUrl = diskPath + "\\" + newfilename; inputStream = file.getInputStream(); outputStream = new FileOutputStream(fileUrl); IOUtils.copy(inputStream, outputStream); relativeFilePath = relativepath + newfilename; result.setRelativepath(relativeFilePath); result.setAbsolutepath(fileUrl); } catch (Exception ignored) { } finally { outputStream.flush(); inputStream.close(); outputStream.close(); } return result; } private static String getExtName(String s, char split) { int i = s.indexOf(split); int leg = s.length(); return (i > 0 ? (i + 1) == leg ? " " : s.substring(i + 1, s.length()) : " "); } private static String getShortNameName(String s, char split) { int i = s.indexOf(split); int leg = s.length(); return (i > 0 ? (i + 1) == leg ? " " : s.substring(0, i) : " "); } public static void writeFile(File f, String content) { writeFile(f, content, "utf-8"); } public static void writeFile(File f, String content, String encode) { try { if (!f.exists()) { f.createNewFile(); } OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f), encode); BufferedWriter utput = new BufferedWriter(osw); utput.write(content); utput.close(); } catch (Exception e) { } } public static void writeFile(String path, String content, String encode) { File f = new File(path); writeFile(f, content, encode); } public static void writeFile(String path, String content) { File f = new File(path); writeFile(f, content, "utf-8"); } public static String readFile(File file) { return readFile(file, "UTF-8"); } public static String readFile(File file, String encode) { String output = ""; if (file.exists()) { if (file.isFile()) { try { InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encode); BufferedReader input = new BufferedReader(isr); StringBuffer buffer = new StringBuffer(); String text; while ((text = input.readLine()) != null) buffer.append(text + "\n"); output = buffer.toString(); } catch (IOException ioException) { System.err.println("File Error!"); } } else if (file.isDirectory()) { String[] dir = file.list(); output += "Directory contents:\n"; for (int i = 0; i < dir.length; i++) { output += dir[i] + "\n"; } } } else { System.err.println("Does not exist!"); } return output; } public static String readFile(String fileName, String encode) { File file = new File(fileName); return readFile(file, encode); } public static String readFile(String fileName) { return readFile(fileName, "utf-8"); } public static List getFiles(String folder) { File file = new File(folder); List files = new ArrayList(); if (file.exists()) { File[] sonFiles = file.listFiles(); if (sonFiles != null && sonFiles.length > 0) { for (int i = 0; i < sonFiles.length; i++) { if (!sonFiles[i].isDirectory()) { files.add(sonFiles[i]); } } } } return files; } public static List getFilesFromFolder(String folder) { File file = new File(folder); List files = new ArrayList(); if (file.exists()) { File[] sonFiles = file.listFiles(); if (sonFiles != null && sonFiles.length > 0) { for (int i = 0; i < sonFiles.length; i++) { if (sonFiles[i].isDirectory()) { files.add(sonFiles[i]); } } } } return files; } public static boolean hasSubfolder(String folder) { File file = new File(folder); return hasSubfolder(file); } public static boolean hasSubfolder(File file) { if (file.exists()) { File[] sonFiles = file.listFiles(); if (sonFiles != null && sonFiles.length > 0) { for (int i = 0; i < sonFiles.length; i++) { if (sonFiles[i].isDirectory()) { return true; } } } } return false; } public static void mkdir(String folder) { File file = new File(folder); if (!file.exists()) { file.mkdirs(); } } public static void copy(File src, File dst) { try { int BUFFER_SIZE = 32 * 1024; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dst); byte[] buffer = new byte[BUFFER_SIZE]; int count; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { } } public static void copyDirectiory(String sourceDir, String targetDir) throws IOException { if (new File(sourceDir).exists()) { // 新建目标目录 File targetFolder = new File(targetDir); if (!targetFolder.exists()) { targetFolder.mkdirs(); } // 获取源文件夹当前下的文件或目录 File[] file = (new File(sourceDir)).listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isFile()) { // 源文件 File sourceFile = file[i]; // 目标文件 File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName()); copy(sourceFile, targetFile); } if (file[i].isDirectory()) { // 准备复制的源文件夹 String dir1 = sourceDir + "/" + file[i].getName(); // 准备复制的目标文件夹 String dir2 = targetDir + "/" + file[i].getName(); copyDirectiory(dir1, dir2); } } } } public static String getExt(File src) { if (src != null) { String name = src.getName(); return name.substring(name.lastIndexOf("."), name.length()); } return ""; } public static String getExt(String src) { if (src != null) { return src.substring(src.lastIndexOf("."), src.length()); } return ""; } public static void del(String path) { File file = new File(path); deleteFile(file); } public static void deleteFile(File file) { if (file.exists()) { //判断文件是否存在 if (file.isFile()) { //判断是否是文件 file.delete(); //delete()方法 你应该知道 是删除的意思; } else if (file.isDirectory()) { //否则如果它是一个目录 File files[] = file.listFiles(); //声明目录下所有的文件 files[]; for (int i = 0; i < files.length; i++) { //遍历目录下所有的文件 deleteFile(files[i]); //把每个文件 用这个方法进行迭代 } } file.delete(); } } public static void upzip() throws Exception { File file = new File("D:\\test.zip");//压缩文件 ZipFile zipFile = new ZipFile(file);//实例化ZipFile,每一个zip压缩文件都可以表示为一个ZipFile //实例化一个Zip压缩文件的ZipInputStream对象,可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象 ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file)); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.getNextEntry()) != null) { String fileName = zipEntry.getName(); File temp = new File("D:\\un\\" + fileName); temp.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(temp); //通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流 InputStream is = zipFile.getInputStream(zipEntry); int len = 0; while ((len = is.read()) != -1) os.write(len); os.close(); is.close(); } zipInputStream.close(); } public static void downloadFile(String path, String name, HttpServletResponse response) throws Exception { // path是指欲下载的文件的路径。 File file = new File(path); try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) { String fileName = URLEncoder.encode(name, "UTF-8"); response.reset(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.addHeader("Content-Length", "" + file.length()); response.setContentType("application/octet-stream;charset=UTF-8"); Files.copy(file, outputStream); outputStream.flush(); } } public static void deleteFile(String filePath) { File file = new File(filePath); if (!file.delete()) { // log.error("Delete file {} error", filePath); } } }