package com.lxzn.framework.utils.file; import com.lxzn.framework.domain.filesystem.response.FileUploadResult; import com.lxzn.framework.domain.nc.response.DocumentCode; import com.lxzn.framework.exception.ExceptionCast; import com.lxzn.framework.utils.SHA256Util; import com.lxzn.framework.utils.date.DateUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Date; import java.util.List; @Slf4j @Component public class FileUtil { private static String fileUploadFolder; @Value("${fileHomePath}") public void setFileUploadFolder(String fileUploadFolder) { FileUtil.fileUploadFolder = fileUploadFolder; } public static FileUploadResult uploadFile(MultipartFile file) { if(file == null || file.isEmpty()) return null; String fileName = file.getOriginalFilename(); String suffix = getFileSuffix(fileName); // if(StringUtils.isBlank(suffix)) // return null; Date currentDate = DateUtil.getNow(); String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH); //相对路径 String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/"; //绝对路径 String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/"; String fileNameNonSuffix = getFilenameNonSuffix(fileName); if(fileNameNonSuffix == null) return null; String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis()); Long fileSize = file.getSize(); boolean b = uploadFile(file, absolutePath, encodeFileName); if(!b) return null; FileUploadResult dto = new FileUploadResult(); dto.setFileName(fileNameNonSuffix); dto.setEncodeFileName(encodeFileName); dto.setFilePath(relativePath); dto.setFileSize(fileSize); dto.setFileSuffix(suffix); return dto; } /** * 方法一:使用 FileWriter 写文件 * @param filepath 文件目录 * @param content 待写入内容 * @throws IOException */ public static void fileWriterSql(String filepath, String content) throws IOException { OutputStreamWriter outputStreamWriter = null; try { File file = new File(filepath); if (!file.exists()){ file.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(file); if (outputStream != null){ outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8"); outputStreamWriter.write(content); outputStreamWriter.flush(); } try { if (outputStreamWriter != null){ outputStreamWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.getMessage(); } finally { try { if (outputStreamWriter != null){ outputStreamWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 删除文件 * * @param filePath * @return */ public static boolean deleteNcFile(String filePath) { String lastFileReName = fileUploadFolder + "/" + filePath ; boolean flag = false; File file = new File(lastFileReName); if (!file.exists()) { return flag; } boolean b = file.delete(); if (!b) { System.out.println("文件删除失败: " + filePath); } return true; } public static boolean copyFileUpName(String lastFile ,String newFile,String ncFix) { String lastFileReName = fileUploadFolder + "/" + lastFile ; if (StringUtils.isNotBlank(ncFix)) { newFile = newFile + "." + ncFix; } File toFile = new File(newFile); if (!toFile.getParentFile().exists()) { toFile.mkdirs(); } try { long begintime = System.currentTimeMillis(); // 获取拷贝文件前的系统时间 Files.copy(Paths.get(lastFileReName), Paths.get(newFile), StandardCopyOption.REPLACE_EXISTING); long endtime = System.currentTimeMillis(); // 获取文件拷贝结束时的系统时间 System.out.println("拷贝文件所消耗的时间是:" + (endtime - begintime) + "毫秒"); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static FileUploadResult uploadFile(String fileName, InputStream fis) { if(fis == null) return null; //String fileName = file.getName(); String suffix = getFileSuffix(fileName); // if(StringUtils.isBlank(suffix)) // return null; Date currentDate = DateUtil.getNow(); String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH); //相对路径 String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/"; //绝对路径 String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/"; String fileNameNonSuffix = getFilenameNonSuffix(fileName); if(fileNameNonSuffix == null) { return null; } String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis()); //Long fileSize = fis; long b = uploadFile(fis, absolutePath, encodeFileName); if(b <= 0) return null; FileUploadResult dto = new FileUploadResult(); dto.setFileName(fileNameNonSuffix); dto.setEncodeFileName(encodeFileName); dto.setFilePath(relativePath); dto.setFileSize(b); dto.setFileSuffix(suffix); return dto; } public static void downLoadFile(HttpServletResponse response, String fileName, String filePath, String toFileName) { String absolutePath = fileUploadFolder + filePath; File file = new File(absolutePath , fileName); if(file.exists()) { byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { response.setHeader("Content-Type", "application/octet-stream;charset=utf-8"); // 告诉浏览器输出内容为流 //response.setHeader("Content-Disposition", "attachment;fileName="+ new String(toFileName.getBytes("UTF-8"),"ISO-8859-1")); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(toFileName, "UTF-8")); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } }catch (Exception e) { log.error(e.getMessage(), e.getStackTrace()); }finally { if(bis != null) { try { bis.close(); } catch (IOException e) { } } if(fis != null) { try { fis.close(); } catch (IOException e) { } } } }else { ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST); } } /** * 上传文件工具类 * @param multipartFile * @param path * @param fileNewName 新的文件名 * @return */ public static boolean uploadFile(MultipartFile multipartFile, String path, String fileNewName) { File targetFile = new File(path, fileNewName); if(!targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdirs(); } try { multipartFile.transferTo(targetFile); return true; } catch (Exception e) { log.error(e.getMessage(), e.getStackTrace()); return false; } } public static long uploadFile(InputStream fis, String path, String fileNewName) { File targetFile = new File(path, fileNewName); if(!targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdirs(); } try { FileOutputStream fos = new FileOutputStream(targetFile); //FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[1024 * 4]; int index = 0; long total = 0; while ((index = fis.read(bytes)) != -1) { fos.write(bytes, 0, index); total =+ index; } fis.close(); fos.flush(); fos.close(); return total; } catch (Exception e) { log.error(e.getMessage()); } return -1; } /** * 删除文件 * * @param filePath * @return */ public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(filePath); if (!file.exists()) { return flag; } boolean b = file.delete(); if (!b) { try { System.gc(); Path path = Paths.get(filePath); Files.deleteIfExists(path); } catch (IOException e) { e.printStackTrace(); } } return true; } /** * * @param file * @return */ public static long selectFileSize(File file) { try (FileInputStream fis = new FileInputStream(file)) { long size = 0; int read; byte[] buffer = new byte[1024]; while ((read = fis.read(buffer)) != -1) { size += read; } return size; } catch (IOException e) { e.printStackTrace(); } return 0; } /** * 获取文件后缀 无后缀文件返回NULL * @param fileName * @return */ public static String getFileSuffix(String fileName) { if (fileName.contains(".")) { String suffix = fileName.substring(fileName.lastIndexOf('.') + 1); return suffix; }else { return null; } } /** * 获取文件名 不带后缀和点号 * @param fileName * @return */ public static String getFilenameNonSuffix(String fileName) { if (fileName.contains(".")) { String filename = fileName.substring(0, fileName.lastIndexOf('.')); return filename; }else { return fileName; } } public static List readFile(String fileEncodeName, String filePath) { String absolutePath = fileUploadFolder + filePath; File file = new File(absolutePath , fileEncodeName); if(!file.exists() || file.isDirectory()) ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST); String charset = checkFileEncode(file); if(charset == null) ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST); List readList = new ArrayList<>(); String tempString = null; BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); while ((tempString = reader.readLine()) != null) { readList.add(tempString); } if(readList.isEmpty()) return null; return readList; } catch (Exception e) { log.error(e.getMessage(), e.getStackTrace()); return null; } finally { if(reader != null) { try { reader.close(); } catch (IOException e) { log.error(e.getMessage(), e.getStackTrace()); } } } } private static String checkFileEncode(File file) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; BufferedInputStream bis = null; try { boolean checked = false; bis = new BufferedInputStream(new FileInputStream(file)); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) return charset; if(first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE ) { charset = "UTF-16LE"; checked = true; }else if ( first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF ) { charset = "UTF-16BE"; checked = true; }else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF ) { charset = "UTF-8"; checked = true; } bis.reset(); if (!checked) { while ((read = bis.read()) != -1 ) { if ( read >= 0xF0 ) break; if ( 0x80 <= read && read <= 0xBF ) // 单独出现BF以下的,也算是GBK break; if ( 0xC0 <= read && read <= 0xDF ) { read = bis.read(); if ( 0x80 <= read && read <= 0xBF ) // 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GBK编码内   continue; else break; } else if ( 0xE0 <= read && read <= 0xEF ) { // 也有可能出错,但是几率较小 read = bis.read(); if ( 0x80 <= read && read <= 0xBF ) { read = bis.read(); if ( 0x80 <= read && read <= 0xBF ) { charset = "UTF-8"; break; } else break; } else { break; } } } } return charset; }catch (Exception e) { return null; }finally { if(bis != null) { try { bis.close(); } catch (IOException e) { } } } } /** * 复制文件 * @param oldPath * @param newPath * @param fileName */ public static boolean copyFile(String oldPath, String newPath, String fileName){ oldPath = fileUploadFolder + oldPath; newPath = fileUploadFolder + newPath; File oldFile = new File(oldPath, fileName); File newFile = new File(newPath, fileName); if(oldFile.exists()){ if(!newFile.getParentFile().exists()){ newFile.getParentFile().mkdirs(); } FileChannel inputChannel = null; FileChannel outputChannel = null; try{ inputChannel = new FileInputStream(oldFile).getChannel(); outputChannel = new FileOutputStream(newFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); return true; }catch (Exception e){ log.error("复制文件错误{}", e); return false; }finally { try { inputChannel.close(); outputChannel.close(); }catch (Exception e){ log.error("复制文件错误{}", e); } } } return false; } public static String getFileAbsPath(String path, String fileName){ path = fileUploadFolder + path; File file = new File(path, fileName); if(file.exists()){ return file.getAbsolutePath(); } return null; } public static String getFileAbsPathTxt(String path){ File file = new File(path); if(file.exists()){ return file.getAbsolutePath(); } return null; } }