package com.vci.starter.web.util; import com.vci.starter.web.exception.VciBaseException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.system.ApplicationHome; import org.springframework.core.io.ClassPathResource; import org.springframework.util.ResourceUtils; import java.io.*; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; /** * 本地文件操作类 * @author weidy */ public class LocalFileUtil { /** * 主类 */ public static Class mainClass = null; /** * 删除文件夹 * @param file 要删除的文件或者文件夹 */ public static void deleteFile(File file) { if(file == null || !file.exists()){ return; } if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFile(files[i]); } } file.delete(); } /** * 拷贝文件 * @param source 源文件 * @param target 目标文件 * @throws VciBaseException 拷贝文件出错的时候会抛出异常 */ public static void copyFile(File source, File target) throws VciBaseException { FileInputStream is = null; FileOutputStream os = null; try{ is = new FileInputStream(source); os = new FileOutputStream(target); FileChannel sourceChannel = is.getChannel(); FileChannel targetChannel = os.getChannel(); int i=0; int length=2097152; while(true){ if(sourceChannel.position()==sourceChannel.size()){ sourceChannel.close(); targetChannel.close(); break; } if((sourceChannel.size()-sourceChannel.position())<20971520) { length = (int) (sourceChannel.size() - sourceChannel.position()); }else { length = 20971520; } sourceChannel.transferTo(sourceChannel.position(),length,targetChannel); sourceChannel.position(sourceChannel.position()+length); i++; } }catch(Throwable e){ throw new VciBaseException("拷贝文件出错",new String[0],e); }finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } /** * 获取默认的临时文件夹 * @return 临时文件夹,默认为当前项目的运行路径下的tempFolder下的随机值 */ public static String getDefaultTempFolder() throws VciBaseException{ String path = getProjectFolder(); path = path + File.separator + "tempFolder" + File.separator + UUID.randomUUID().toString(); File folder = new File(path); if(!folder.exists()){ folder.mkdirs(); } return path; } /** * 获取项目的路径 * @return 项目的路径 * @throws VciBaseException 获取路径出现了错误会抛出异常 */ public static String getProjectFolder() throws VciBaseException{ return getProjectFolder(LocalFileUtil.class); } /** * 获取某个class所在项目的路径 * @param classObj 某个class * @return 项目的路径 * @throws VciBaseException 获取路径出现了错误会抛出异常 */ public static String getProjectFolder(Class classObj) throws VciBaseException{ String path = ""; try { ApplicationHome h = new ApplicationHome(classObj == null?(mainClass ==null?LocalFileUtil.class:mainClass):classObj); File jarF = h.getSource(); if(jarF == null){ //针对测试的时候 jarF = h.getDir(); } path = jarF.getParentFile().toString(); if(path.contains("!")){ path = new File(path).getParentFile().getParent(); } }catch (Throwable e){ e.printStackTrace(); throw new VciBaseException("获取当前服务所在的文件夹出现了错误",new String[0],e); } if(path.startsWith("file:\\")){ path = path.substring(6); } if (System.getProperty("os.name").toLowerCase().startsWith("win") && path.startsWith("/")) { path = path.substring(path.indexOf("/") + 1); } System.out.println("项目的路径是:" + path); return path; } /** * 删除临时文件 * @param tempFile 临时文件 * @param deleteRandomFolder 是否删除随机的那个文件夹 * @throws VciBaseException 删除出错的时候抛出异常 */ public static void deleteTempFile(File tempFile,boolean deleteRandomFolder) throws VciBaseException{ if(tempFile!=null){ tempFile.delete(); if(deleteRandomFolder){ tempFile.getParentFile().delete(); } } } /** * 判断参数是否为空 * @param s 参数,第一个为参数,第二个为提示信息 * @throws VciBaseException 为空时抛出这个异常 */ public static void alertNotNull(Object... s) throws VciBaseException{ if(s!=null && s.length>0){ for(int i = 0 ; i < s.length ; i ++){ Object obj = s[i]; if(obj==null ||StringUtils.isBlank(obj.toString())){ String param = ""; try{ i++; param = s[i].toString(); }catch(Exception e){ } throw new VciBaseException("参数[" + param + "]不能为空"); } } } } /** * 获取文件的后缀名 * @param file 文件对象 * @return 后缀名,不包含.;如果文件不存在或者没有后缀名返回"" */ public static String getFileExtension(File file){ if(file!=null){ return getFileExtensionByName(file.getName()); } return ""; } /** * 获取文件的后缀名 * @param name 文件名称 * @return 后缀名,不包含.;没有后缀名返回"" */ public static String getFileExtensionByName(String name){ if(StringUtils.isNotBlank(name)){ if(name.contains(".")){ return name.substring(name.lastIndexOf(".")+1); } } return ""; } /** * 获取上传文件的名称,在IE浏览器上,上传会把全路径带过来 * @param name 文件的名称 * @return 替换后的值 */ public static String getFileNameForIE(String name){ if(StringUtils.isBlank(name)){ return name; } if(name.contains(File.separator)){ return name.substring(name.lastIndexOf(File.separator)+1); } if(name.contains("\\")){ return name.substring(name.lastIndexOf("\\") + 1); } return name; } /** * 从工程中读取文件的内容 * @param fileName 文件的名称 * @return 文件的内容 * @throws VciBaseException 读取出错的时候会抛出异常 */ public static String readContentForFileInJar(String fileName) throws VciBaseException{ if(StringUtils.isBlank(fileName)){ throw new VciBaseException("文件名为空"); } if(!fileName.startsWith("/")){ fileName = "/" + fileName; } InputStream in = null; ByteArrayOutputStream os = null; try{ in = LocalFileUtil.class.getResourceAsStream( fileName); if(in ==null){ in=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } os = new ByteArrayOutputStream(); IOUtils.copy(in,os); return new String(os.toByteArray(),"UTF-8"); }catch (Throwable e){ throw new VciBaseException("读取文件的内容出现了错误",new String[0],e); }finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(os); } } /** * 读取文件的内容,文件不能是jar里的 * @param fileName 文件的名称 * @return 文件的内容,是UTF-8的字符集 * @throws VciBaseException 文件不存在,和读取出错的时候会抛出异常 */ public static String readContentForFile(String fileName) throws VciBaseException{ File file = new File(fileName); if(!file.exists()){ throw new VciBaseException("文件未找到,{0}",new String[]{fileName}); } InputStream in = null; ByteArrayOutputStream os = null; try{ in = new FileInputStream( file); os = new ByteArrayOutputStream(); IOUtils.copy(in,os); return new String(os.toByteArray(),"UTF-8"); }catch (Throwable e){ throw new VciBaseException("读取文件的内容出现了错误",new String[0],e); }finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(os); } } /** * 写入字符串到文件 * @param content 字符串 * @param fileName 文件的名称 * @throws VciBaseException 写入出错的时候会抛出异常 */ public static void writeContentToFile(String content,String fileName) throws VciBaseException{ File file = new File(fileName); if(!file.exists()){ File parentFile = file.getParentFile(); if(!parentFile.exists()){ parentFile.mkdirs(); } try { file.createNewFile(); } catch (IOException e) { throw new VciBaseException("写入文件的内容时候出现了创建文件失败的问题,{}",new String[]{fileName},e); } } if(content == null){ content = ""; } OutputStream os = null; try{ os = new FileOutputStream(file); os.write(content.getBytes(StandardCharsets.UTF_8)); os.flush(); }catch(Throwable e){ throw new VciBaseException("写入文件的内容时候出现了创错误,{}",new String[]{fileName},e); }finally { IOUtils.closeQuietly(os); } } /** * 从项目里或者jar的文件到目标文件 * @param fileInJar jar或者项目里的文件名称 * @param target 目标文件 * @throws VciBaseException 拷贝文件出现错误的时候会抛出异常 */ public static void copyFileInJar(String fileInJar,String target) throws VciBaseException{ VciBaseUtil.alertNotNull(fileInJar,"源文件",target,"目标文件"); File targetFile = new File(target); File folder = targetFile.getParentFile(); if(!folder.exists()){ folder.mkdirs(); } if(!targetFile.exists()){ try { targetFile.createNewFile(); } catch (IOException e) { throw new VciBaseException("创建目标文件的出现了错误",new String[0],e); } } if(!fileInJar.startsWith("/")){ fileInJar = "/" + fileInJar; } InputStream in = null; FileOutputStream os = null; try{ in = LocalFileUtil.class.getResourceAsStream( fileInJar); if(in ==null){ in=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileInJar); } os = new FileOutputStream(target); IOUtils.copy(in,os); }catch (Throwable e){ throw new VciBaseException("拷贝文件的内容出现了错误.{0},{1}",new String[]{fileInJar,target},e); }finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(os); } } /** * 文件转换为路径 * @param fileList 文件列表 * @return 路径列表 * @throws VciBaseException 参数为空和文件不存在会抛出异常 */ public static List fileToPatch(Collection fileList) throws VciBaseException { VciBaseUtil.alertNotNull("文件列表",fileList); List filePath = new ArrayList<>(); for(File file : fileList){ if(!file.exists()){ throw new VciBaseException(file.getAbsolutePath() + "文件没有找到",new String[0]); } filePath.add(file.getAbsolutePath()); } return filePath; } /** * 获取图片专用的临时路径 * @return 路径 * @throws VciBaseException 获取出错会报错 */ public static String getDefaultPicTempFolder() throws VciBaseException{ String path = LocalFileUtil.getProjectFolder(); path = path + File.separator + "tempFolder" + File.separator + "picFolder" + File.separator ; File folder = new File(path); if(!folder.exists()){ folder.mkdirs(); } return path; } }