fhx
2024-03-26 818d25c9d778b0780b917b190714df66ead250d1
提交 | 用户 | age
c1a9ee 1 package com.hx.util;
F 2
0a4d0a 3 import com.hx.exception.TipsException;
c1a9ee 4 import org.apache.commons.fileupload.FileItem;
F 5 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
6 import org.apache.commons.io.IOUtils;
7 import org.springframework.http.MediaType;
8 import org.springframework.web.multipart.MultipartFile;
9 import org.springframework.web.multipart.commons.CommonsMultipartFile;
248c35 10 import sun.misc.BASE64Decoder;
0a4d0a 11 import sun.misc.BASE64Encoder;
c1a9ee 12
F 13 import java.io.*;
14 import java.net.URL;
15 import java.net.URLConnection;
16 import java.util.Base64;
17
18 /**
19  * 文件转换工具类
20  * @USER: fhx
21  * @DATE: 2022/3/2
22  **/
23 public class FileConvertTool {
24
25     private static final int  BUFFER_SIZE = 2 * 1024;
26
27
28     /** 获取网络路径文件流 */
29     public static InputStream getUrlFile(String urlPath) throws IOException {
30         if(StringUtils.isEmpty(urlPath)){
31             return null;
32         }
33         // 构造URL
34         URL url = new URL(urlPath);
35         // 打开连接
36         URLConnection con = url.openConnection();
37         //设置请求超时为5s
38         con.setConnectTimeout(5*1000);
39         // 输入流
40         InputStream is = con.getInputStream();
41         return is;
42     }
43
44     /**
45      * 获取文件base64字符串
46      * @param urlPath  文件路径
c123f9 47      * @return 返回base64编码
c1a9ee 48      */
F 49     public static String getFileBaseStrByUrl(String urlPath) throws IOException {
50         InputStream is = getUrlFile(urlPath);
51         byte[] bytes = IOUtils.toByteArray(is);
52         String encoded = Base64.getEncoder().encodeToString(bytes);
53         return encoded;
54     }
55
56     // inputStream转outputStream
57     public static ByteArrayOutputStream parse(final InputStream in) throws Exception {
58         final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
59         int ch;
60         while ((ch = in.read()) != -1) {
61             swapStream.write(ch);
62         }
63         return swapStream;
64     }
65
66     // outputStream转inputStream
67     public static ByteArrayInputStream parse(final OutputStream out) throws Exception {
68         ByteArrayOutputStream baos = new ByteArrayOutputStream();
69         baos = (ByteArrayOutputStream) out;
70         final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
71         return swapStream;
72     }
73
74     // inputStream转String
75     public static String parse_String(final InputStream in) throws Exception {
76         final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
77         int ch;
78         while ((ch = in.read()) != -1) {
79             swapStream.write(ch);
80         }
81         return swapStream.toString();
82     }
83
84     // OutputStream 转String
85     public static String parse_String(final OutputStream out) throws Exception {
86         ByteArrayOutputStream baos = new ByteArrayOutputStream();
87         baos = (ByteArrayOutputStream) out;
88         final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
89         return swapStream.toString();
90     }
91
92     // String转inputStream
93     public static ByteArrayInputStream parse_inputStream(final String in) throws Exception {
94         final ByteArrayInputStream input = new ByteArrayInputStream(in.getBytes());
95         return input;
96     }
97
98     // String 转outputStream
99     public static ByteArrayOutputStream parse_outputStream(final String in) throws Exception {
100         return parse(parse_inputStream(in));
101     }
102
103     /**
104      * 根据byte数组,生成文件
105      */
106     public static File getFile(byte[] bfile, String filePath,String fileName) {
107         BufferedOutputStream bos = null;
108         FileOutputStream fos = null;
109         File file = null;
110         try {
111             File dir = new File(filePath);
0b6e55 112             if(!dir.exists()){//判断文件目录是否存在
c1a9ee 113                 dir.mkdirs();
F 114             }
115             file = new File(filePath+"\\"+fileName);
116             fos = new FileOutputStream(file);
117             bos = new BufferedOutputStream(fos);
118             bos.write(bfile);
119         } catch (Exception e) {
120             e.printStackTrace();
121         } finally {
122             if (bos != null) {
123                 try {
124                     bos.close();
125                 } catch (IOException e1) {
126                     e1.printStackTrace();
127                 }
128             }
129             if (fos != null) {
130                 try {
131                     fos.close();
132                 } catch (IOException e1) {
133                     e1.printStackTrace();
134                 }
135             }
136         }
137         return file;
138     }
139
140     /**
141      * 根据byte数组,生成文件
142      */
143     public static File getFile(InputStream in, String filePath, String fileName) {
144         if(in == null){
145             return null;
146         }
147         BufferedOutputStream bos = null;
148         FileOutputStream fos = null;
149         File file = null;
150         try {
151             File dir = new File(filePath);
152             //判断文件目录是否存在
153             if(!dir.exists()){
154                 dir.mkdirs();
155             }
156             file = new File(filePath+"/"+fileName);
157             fos = new FileOutputStream(file);
158             byte[] b = new byte[BUFFER_SIZE];
159 //            while ((in.read(b)) != -1) {
160 //                fos.write(b); // 写入数据
161 //            }
162             int len;
163             while ((len = in.read(b)) != -1){
164                 fos.write(b, 0, len);
165             }
166             in.close();
167         } catch (Exception e) {
168             e.printStackTrace();
169         } finally {
170             if (bos != null) {
171                 try {
172                     bos.close();
173                 } catch (IOException e1) {
174                     e1.printStackTrace();
175                 }
176             }
177             if (fos != null) {
178                 try {
179                     fos.close();
180                 } catch (IOException e1) {
181                     e1.printStackTrace();
182                 }
183             }
184         }
185         return file;
186     }
187
188     /**
189      * 获得指定文件的byte数组
190      */
191     private static byte[] getBytes(String filePath){
192         byte[] buffer = null;
193         try {
194             File file = new File(filePath);
195             FileInputStream fis = new FileInputStream(file);
196             ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
197             byte[] b = new byte[1000];
198             int n;
199             while ((n = fis.read(b)) != -1) {
200                 bos.write(b, 0, n);
201             }
202             fis.close();
203             bos.close();
204             buffer = bos.toByteArray();
205         } catch (FileNotFoundException e) {
206             e.printStackTrace();
207         } catch (IOException e) {
208             e.printStackTrace();
209         }
210         return buffer;
211     }
212
213     public static MultipartFile getMultipartFile(File file) {
214         FileItem item = new DiskFileItemFactory().createItem("file"
215                 , MediaType.MULTIPART_FORM_DATA_VALUE
216                 , true
217                 , file.getName());
218         try (InputStream input = new FileInputStream(file);
219              OutputStream os = item.getOutputStream()) {
220             // 流转移
221             IOUtils.copy(input, os);
222         } catch (Exception e) {
223             throw new IllegalArgumentException("Invalid file: " + e, e);
224         }
225
226         return new CommonsMultipartFile(item);
227     }
228
229     /**
230      *  根据路径删除指定的目录或文件,无论存在与否
231      *@param sPath  要删除的目录或文件
232      *@return 删除成功返回 true,否则返回 false。
233      */
234     public static boolean deleteFolder(String sPath) {
235         File file = new File(sPath);
236         // 判断目录或文件是否存在
237         if (!file.exists()) {
238             // 不存在返回 true
239             return true;
240         } else {
241             // 判断是否为文件
242             if (file.isFile()) {  // 为文件时调用删除文件方法
243                 return deleteFile(sPath);
244             } else {  // 为目录时调用删除目录方法
245                 return deleteDirectory(sPath);
246             }
247         }
248     }
249
250     /**
251      * 删除单个文件
252      * @param   sPath    被删除文件的文件名
253      * @return 单个文件删除成功返回true,否则返回false
254      */
255     public static boolean deleteFile(String sPath) {
256         File  file = new File(sPath);
257         // 路径为文件且不为空则进行删除
258         if (file.isFile() && file.exists()) {
259             file.delete();
260             return true;
261         }
262         return false;
263     }
264
265     /**
818d25 266      * 删除单个文件
F 267      * @param   file    被删除文件
268      * @return 单个文件删除成功返回true,否则返回false
269      */
270     public static boolean deleteFile(File file) {
271         if(file == null){
272             return true;
273         }
274         // 路径为文件且不为空则进行删除
275         if (file.isFile() && file.exists()) {
276             file.delete();
277             return true;
278         }
279         return false;
280     }
281
282     /**
c1a9ee 283      * 删除目录(文件夹)以及目录下的文件
F 284      * @param   sPath 被删除目录的文件路径
285      * @return  目录删除成功返回true,否则返回false
286      */
287     public static boolean deleteDirectory(String sPath) {
288         //如果sPath不以文件分隔符结尾,自动添加文件分隔符
289         if (!sPath.endsWith(File.separator)) {
290             sPath = sPath + File.separator;
291         }
292         File dirFile = new File(sPath);
293         //如果dir对应的文件不存在,或者不是一个目录,则退出
294         if (!dirFile.exists() || !dirFile.isDirectory()) {
295             return false;
296         }
297         boolean flag = true;
298         //删除文件夹下的所有文件(包括子目录)
299         File[] files = dirFile.listFiles();
300         for (int i = 0; i < files.length; i++) {
301             //删除子文件
302             if (files[i].isFile()) {
303                 flag = deleteFile(files[i].getAbsolutePath());
304                 if (!flag) break;
305             } //删除子目录
306             else {
307                 flag = deleteDirectory(files[i].getAbsolutePath());
308                 if (!flag) break;
309             }
310         }
311         if (!flag) return false;
312         //删除当前目录
313         if (dirFile.delete()) {
314             return true;
315         } else {
316             return false;
317         }
318     }
248c35 319
0a4d0a 320     public static String encodeBase64File(File file) throws Exception {
F 321         FileInputStream fileInputStream = new FileInputStream(file);
322         byte[] bytes = new byte[fileInputStream.available()];
323         // 读取到 byte 里面
324         fileInputStream.read(bytes);
325         fileInputStream.close();
326         BASE64Encoder base64Encoder = new BASE64Encoder();
327         // 得到文件 之后转成beye 然后使用base64转码
328         // 转码
329         String encode = base64Encoder.encode(bytes);
330          return encode;
331     }
248c35 332
0a4d0a 333     public static String encodeBase64File(MultipartFile multipartFile) throws Exception {
F 334         if (multipartFile == null) {
335             throw new TipsException("未检查到上传的文件!");
336         }
337         String imageBaseStr = null;
338         try {
339             String contentType = multipartFile.getContentType();
340             byte[] imageBytes = multipartFile.getBytes();
341             BASE64Encoder base64Encoder = new BASE64Encoder();
342 //            imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
343             imageBaseStr = base64Encoder.encode(imageBytes);
344             imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", "");
345         } catch (IOException e) {
346             throw new TipsException("文件转换base64异常");
347         }
348         //返回生成的编码
349         return imageBaseStr;
350     }
c1a9ee 351 }