package com.hx.util; import com.hx.exception.TipsException; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.io.IOUtils; import org.springframework.http.MediaType; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.Base64; /** * 文件转换工具类 * @USER: fhx * @DATE: 2022/3/2 **/ public class FileConvertTool { private static final int BUFFER_SIZE = 2 * 1024; /** 获取网络路径文件流 */ public static InputStream getUrlFile(String urlPath) throws IOException { if(StringUtils.isEmpty(urlPath)){ return null; } // 构造URL URL url = new URL(urlPath); // 打开连接 URLConnection con = url.openConnection(); //设置请求超时为5s con.setConnectTimeout(5*1000); // 输入流 InputStream is = con.getInputStream(); return is; } /** * 获取文件base64字符串 * @param urlPath 文件路径 * @return 返回base64编码 */ public static String getFileBaseStrByUrl(String urlPath) throws IOException { InputStream is = getUrlFile(urlPath); byte[] bytes = IOUtils.toByteArray(is); String encoded = Base64.getEncoder().encodeToString(bytes); return encoded; } // inputStream转outputStream public static ByteArrayOutputStream parse(final InputStream in) throws Exception { final ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) { swapStream.write(ch); } return swapStream; } // outputStream转inputStream public static ByteArrayInputStream parse(final OutputStream out) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos = (ByteArrayOutputStream) out; final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray()); return swapStream; } // inputStream转String public static String parse_String(final InputStream in) throws Exception { final ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) { swapStream.write(ch); } return swapStream.toString(); } // OutputStream 转String public static String parse_String(final OutputStream out) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos = (ByteArrayOutputStream) out; final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray()); return swapStream.toString(); } // String转inputStream public static ByteArrayInputStream parse_inputStream(final String in) throws Exception { final ByteArrayInputStream input = new ByteArrayInputStream(in.getBytes()); return input; } // String 转outputStream public static ByteArrayOutputStream parse_outputStream(final String in) throws Exception { return parse(parse_inputStream(in)); } /** * 根据byte数组,生成文件 */ public static File getFile(byte[] bfile, String filePath,String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if(!dir.exists()){//判断文件目录是否存在 dir.mkdirs(); } file = new File(filePath+"/"+fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bfile); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; } /** * 根据byte数组,生成文件 */ public static File getFile(InputStream in, String filePath, String fileName) { if(in == null){ return null; } BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); //判断文件目录是否存在 if(!dir.exists()){ dir.mkdirs(); } file = new File(filePath+"/"+fileName); fos = new FileOutputStream(file); byte[] b = new byte[BUFFER_SIZE]; // while ((in.read(b)) != -1) { // fos.write(b); // 写入数据 // } int len; while ((len = in.read(b)) != -1){ fos.write(b, 0, len); } in.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; } /** * 获得指定文件的byte数组 */ private static byte[] getBytes(String filePath){ byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } public static MultipartFile getMultipartFile(File file) { FileItem item = new DiskFileItemFactory().createItem("file" , MediaType.MULTIPART_FORM_DATA_VALUE , true , file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = item.getOutputStream()) { // 流转移 IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } return new CommonsMultipartFile(item); } /** * 根据路径删除指定的目录或文件,无论存在与否 *@param sPath 要删除的目录或文件 *@return 删除成功返回 true,否则返回 false。 */ public static boolean deleteFolder(String sPath) { File file = new File(sPath); // 判断目录或文件是否存在 if (!file.exists()) { // 不存在返回 true return true; } else { // 判断是否为文件 if (file.isFile()) { // 为文件时调用删除文件方法 return deleteFile(sPath); } else { // 为目录时调用删除目录方法 return deleteDirectory(sPath); } } } /** * 删除单个文件 * @param sPath 被删除文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFile(String sPath) { File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); return true; } return false; } /** * 删除单个文件 * @param file 被删除文件 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFile(File file) { if(file == null){ return true; } // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); return true; } return false; } /** * 删除目录(文件夹)以及目录下的文件 * @param sPath 被删除目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String sPath) { //如果sPath不以文件分隔符结尾,自动添加文件分隔符 if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); //如果dir对应的文件不存在,或者不是一个目录,则退出 if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; //删除文件夹下的所有文件(包括子目录) File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { //删除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) break; } //删除子目录 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) break; } } if (!flag) return false; //删除当前目录 if (dirFile.delete()) { return true; } else { return false; } } public static String encodeBase64File(File file) throws Exception { FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[fileInputStream.available()]; // 读取到 byte 里面 fileInputStream.read(bytes); fileInputStream.close(); BASE64Encoder base64Encoder = new BASE64Encoder(); // 得到文件 之后转成beye 然后使用base64转码 // 转码 String encode = base64Encoder.encode(bytes); return encode; } public static String encodeBase64File(MultipartFile multipartFile) throws Exception { if (multipartFile == null) { throw new TipsException("未检查到上传的文件!"); } String imageBaseStr = null; try { String contentType = multipartFile.getContentType(); byte[] imageBytes = multipartFile.getBytes(); BASE64Encoder base64Encoder = new BASE64Encoder(); // imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes); imageBaseStr = base64Encoder.encode(imageBytes); imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", ""); } catch (IOException e) { throw new TipsException("文件转换base64异常"); } //返回生成的编码 return imageBaseStr; } }