package com.miniframe.tools; import com.miniframe.constant.MFConstant; import com.miniframe.core.exception.BusinessException; import com.miniframe.core.ext.UtilTools; import com.miniframe.generate.appcode.FileType; import com.miniframe.model.system.SysFile; import com.miniframe.model.system.dao.SysFileMapper; import com.miniframe.spring.properties.MFMiniCoreProperties; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class XIFileUtils { private static Logger logger = LoggerFactory.getLogger(XIFileUtils.class); private final static String fileRootPathStr = "/cephfs"; static { // IniFileReader reader = new IniFileReader(IniFileReader.defaultConfig); // String pathStr = reader.getStrValue("fileuploadpath"); // if(UtilTools.isNullOrBlank(pathStr)){ // pathStr = XIConfig.fileRootPath; // } // fileRootPathStr =Paths.get(pathStr).toString().replace("\\", XIConfig.separator)+XIConfig.separator; } public static void fileCopy(String sourcePath ,String destinationPath){ File sourceFile = new File(sourcePath); File destinationFile = new File(destinationPath); try { FileUtils.copyFile(sourceFile, destinationFile); // 拷贝文件到目标位置,如果目标文件已存在,会被覆盖。 System.out.println("文件拷贝成功!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws BusinessException { //TODO 解析 边界文件 生成瓦斯积聚区数据 File bfFile =new File("D://pipes3.inp"); List fileStrs =new ArrayList<>(); try{ FileReader fileReader = new FileReader(bfFile); BufferedReader reader = new BufferedReader(fileReader); String line; int linNum =1; while ((line = reader.readLine()) != null) { fileStrs.add(line); } fileReader.close(); reader.close(); }catch (Exception e){ System.out.println(e); throw new BusinessException("EB3100021"); } if(fileStrs.size()<=3){ throw new BusinessException("EB3100025"); } boolean isBlockStart =false; boolean isBlockNumStart =false; int blockNum =0; List blockNames =new ArrayList<>(); for (int i = 3; i < fileStrs.size(); i++) { if(!isBlockStart){ isBlockStart=true; blockNames.add(fileStrs.get(i)); continue; } if(!isBlockNumStart){ blockNum = Integer.valueOf(fileStrs.get(i)); isBlockNumStart=true; continue; } int j = 0; int dyhang =0; for (; j < blockNum; j++) { String line =fileStrs.get(i+dyhang+j); String[] t =line.trim().split(" "); int last =Integer.valueOf(t[t.length-1]); if(last==-1){ ++dyhang; } } i=i+dyhang+blockNum; isBlockStart=false; isBlockNumStart=false; } System.out.println(blockNames); } public static String replacekg(String line){ while (line.lastIndexOf(" ")>0){ String s =line.replace(" "," "); return replacekg(s); } return line; } public static String getRelativizePathStr(Path path) { String relativizePath = null; try { Path rootPath = Paths.get(getRootPathStr()); if (XIPlatformUtils.isWindows()) { rootPath = Paths.get(getRootPathStr()).toRealPath(); path = path.toRealPath(); } relativizePath = rootPath.relativize(path).toString().replace("\\", MFConstant.separator); } catch (IOException e) { e.printStackTrace(); } return relativizePath; } public static String getRelativizePathStr(String pathStr) { return getRelativizePathStr(Paths.get(pathStr)); } public static Path getAbsolutePath(String relativizePathStr) { Path path = Paths.get(getRootPathStr()).resolve(Paths.get(relativizePathStr)); return path; } public static String getAbsolutePathStr(String relativizePathStr) { String absolutePath = getAbsolutePath(relativizePathStr).toString().replace("\\", MFConstant.separator); return absolutePath; } public static String getFileName(String pathStr) { Path path = Paths.get(pathStr); return path.getFileName().toString(); } public static Long getFileSize(String pathStr) throws IOException { Path path = Paths.get(pathStr); if(Files.exists(path)) { return Files.size(path); } return null; } public static String getRootPathStr() { return fileRootPathStr; } /** * 根据hash文件转存 * * @param fileFromPathStr 原文件 * @param group 分组 * @return 转储后的路径 */ public static String restorageFile(String fileFromPathStr, String group) throws IOException { String parentPath = getRootPathStr(); Path pathFrom = Paths.get(fileFromPathStr); if (Files.exists(pathFrom)) { String fileName = pathFrom.getFileName().toString(); String md5 = XIUtils.getMD5(fileName); String uploadDirStr = ""; for (int i = 0; i < MFMiniCoreProperties.getInstance().getFileuploadlevel(); i++) { uploadDirStr += md5.substring(i * 2, i * 2 + 2) + "/"; } Path pathTo = Paths.get(parentPath, group, uploadDirStr, fileName); mkdir(pathTo.getParent()); //覆盖+属性 Files.move(pathFrom, pathTo, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); return getRelativizePathStr(pathTo); } return null; } public static String saveUploadFiles(String files, String userid, String fileMedia) throws Exception { return saveUploadFiles(files, userid, fileMedia, null, null, null, 1, null,1,1,null); } public static String saveUploadFiles(String files, String userid, String fileMedia,String bFid) throws Exception { return saveUploadFiles(files, userid, fileMedia, null, null, null, 1, null,1,1,bFid); } public static String saveUploadFiles(String files, String userid, String fileMedia, String fileType, String fileStartTime, String fileInfo, int fileNameType, String needOp, Integer chunk, Integer chunks, String bFid ) throws Exception { String fileIds = ""; if (UtilTools.isNotNullAndBlank(files)) { List fileList = new ArrayList<>(); if (files.contains(";")) { String[] fileArray = files.split(";"); if (fileArray != null) { for (int i = 0; i < fileArray.length; i++) { fileList.add(fileArray[i]); } } } else { fileList.add(files); } for (String pathStr : fileList) { if (UtilTools.isNotNullAndBlank(pathStr)) { Path path = Paths.get(pathStr); String fielRelativePath = XIFileUtils.getRelativizePathStr(path); SysFile sysFile = new SysFile(); sysFile.setId(UtilTools.getUUid()); if (fileNameType == 0) { sysFile.setFilename(path.getFileName().toString()); } else { //去掉uid部分 int pathIndex = path.getFileName().toString().indexOf("-"); if (pathIndex >= 0 && pathIndex < path.getFileName().toString().length() - 1) { sysFile.setFilename(path.getFileName().toString().substring(pathIndex + 1)); } else { sysFile.setFilename(path.getFileName().toString()); } } if (UtilTools.isNullOrBlank(fileStartTime)) { sysFile.setLasttime(XIDateTimeUtils.getNowDate()); } else { sysFile.setLasttime(XIDateTimeUtils.getDateFromZonedStr(fileStartTime)); } sysFile.setUid(userid); sysFile.setFilesize(BigDecimal.valueOf(Files.size(path))); sysFile.setHashcode(XIUtils.getSHA(path)); sysFile.setFilemedia(fileMedia); sysFile.setRemarks(fileInfo); if (UtilTools.isNotNullAndBlank(fileType)) { sysFile.setFiletype(fileType); } else { sysFile.setFiletype(getFileType(path.getFileName().toString())); } if (UtilTools.isNotNullAndBlank(needOp)) { sysFile.setNeedop(needOp); } sysFile.setFilepath(fielRelativePath); sysFile.setChunk(chunk); sysFile.setChunks(chunks); sysFile.setParentid(bFid); SysFileMapper sysFileDAO = UtilTools.getBean(SysFileMapper.class); sysFileDAO.insertSelective(sysFile); if (fileIds.isEmpty()) { fileIds += sysFile.getId(); } else { fileIds += ";" + sysFile.getId(); } } } } return fileIds; } public static void initHeadFile(){ try { SysFileMapper sysFileMapper = UtilTools.getBean(SysFileMapper.class); SysFile sysFile = sysFileMapper.selectByPrimaryKey("head"); if (sysFile == null) { sysFile = new SysFile(); sysFile.setId("head"); sysFile.setFilename("head.png"); sysFile.setFilepath("head.png"); sysFile.setLasttime(XIDateTimeUtils.getNowDate()); sysFileMapper.insertSelective(sysFile); } }catch (Exception e){} } public static void delete(String filePathStr) { try { Files.deleteIfExists(Paths.get(filePathStr)); } catch (IOException e) { e.printStackTrace(); } } public static String getExtension(String filePathStr) { Path path = Paths.get(filePathStr); String suffix = FilenameUtils.getExtension(path.getFileName().toString()); if (UtilTools.isNullOrBlank(suffix)) { suffix = ""; } return suffix; } public static String getExtensionWithDot(String filePathStr) { Path path = Paths.get(filePathStr); String suffix = FilenameUtils.getExtension(path.getFileName().toString()); if (UtilTools.isNotNullAndBlank(suffix)) { suffix = "." + suffix; } else { suffix = ""; } return suffix; } public static String getFilePathStr(String first, String... more) { Path path = Paths.get(first, more); return path.toString().replace("\\", MFConstant.separator); } public static String getFileType(String fileName) { String fileType = FileType.other.getIndex(); String suffix = getExtension(fileName); if (UtilTools.isNotNullAndBlank(suffix)) { if (suffix.toLowerCase().matches("^(mp3|wav|aac)$")) { fileType = FileType.audio.getIndex(); } else if (suffix.toLowerCase().matches("^(mp4|mpeg4)$")) { fileType = FileType.video.getIndex(); } else if (suffix.toLowerCase().matches("^(jpg|png|jpeg|bmp)$")) { fileType = FileType.image.getIndex(); } } return fileType; } public static boolean mkdir(Path dirPath) { try { if (!Files.exists(dirPath)) { Files.createDirectories(dirPath); } return true; } catch (IOException e) { logger.error("mkdir " + dirPath + " " + e); } return false; } public static boolean mkdir(String dir) { return mkdir(Paths.get(dir)); } public static String getFileUrl(String fileId) throws SQLException { SysFileMapper sysFileDAO = UtilTools.getBean(SysFileMapper.class); SysFile sysFile = sysFileDAO.selectByPrimaryKey(fileId); if (sysFile != null) { return sysFile.getFilepath(); } return ""; } public static boolean isFileExist(String filePathStr) { return Files.exists(Paths.get(filePathStr)); } /** * 读取文件内容,作为字符串返回 */ public static String readFileAsString(String filePathStr) throws IOException { Path path = Paths.get(filePathStr); if (Files.notExists(path)) { throw new FileNotFoundException(filePathStr); } else { return new String(Files.readAllBytes(path)); } } /** * 根据文件路径读取byte[] 数组 */ public static byte[] readFileByBytes(String filePathStr) throws IOException { Path path = Paths.get(filePathStr); if (Files.notExists(path)) { throw new FileNotFoundException(filePathStr); } else { return Files.readAllBytes(path); } } public static String getFileNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } // // public static byte[] getResourceFileBytes(String resourcePath) throws Exception { // // byte[] fileBytes = null; // try { // fileBytes = IOUtils.toByteArray((BufferedInputStream) Resources.getResource(resourcePath).getContent()); // } catch (IOException e) { // throw new Exception("get file by path err : " + e.getMessage()); // } // return fileBytes; // // } public static byte[] getFileBytes(String filePath) throws Exception { byte[] fileBytes = null; try { fileBytes = Files.readAllBytes(Paths.get(filePath)); } catch (IOException e) { throw new Exception("get file by path err : " + e.getMessage()); } return fileBytes; } public static List getCertFilesByPath(String certPath) { List fileList = new ArrayList<>(); Path filePath=Paths.get(certPath); if(Files.exists(filePath) && Files.isDirectory(filePath)){ { try { fileList = Files.walk(filePath) .filter(path -> path.toFile().isFile() && path.toFile().getName().endsWith(".crt")) .map(Path::toString) //.map(path-> path.replace("\\","/")) //.distinct() .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } } } return fileList; } public static String getResourceFilePath(String resourcePath) { return System.getProperty("user.dir") + "/src/main/resources/" + resourcePath; } public static String saveUploadFiles(String filePath, String userid, Integer chunk, Integer chunks, String bFid) throws Exception { return saveUploadFiles(filePath, userid, null, null, null, null, 1, null,chunk,chunks,bFid); } }