chenjiahe
2022-08-19 e7c3ff19f5abea1f1510503b46f99c6ad3870410
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import com.hx.exception.TipsException;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.web.multipart.MultipartFile;
7
8 import java.io.*;
f0ed6f 9 import java.net.FileNameMap;
C 10 import java.net.URLConnection;
5c5945 11 import java.text.SimpleDateFormat;
E 12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Date;
15 import java.util.List;
16
17 /** 文件处理工具
18  * @author ChenJiaHe
19  * @Date 2020-06-17
20  */
21 public class FileUtils {
22
23     private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);
24
25     private static int BUFFER_SIZE = 1024;
26
27     /**
28      * @param path
29      * @MethodName fileIsExists
30      * @Description 文件是否存在
31      * @Author ChenJiaHe
32      * @Date 2019/9/7 9:13
33      * @Since JDK 1.8
34      */
35     public static boolean fileIsExists(String path) {
36         File file = new File(path);
37         if (file.exists()) {
38             return true;
39         } else {
40             return false;
41         }
42     }
43
44     /**
45      * @param sourceFile
46      * @param targetFile
47      * @MethodName copyFile
48      * @Description 复制文件
49      * @Author ChenJiaHe
50      * @Date 2019/9/7 9:36
51      * @Since JDK 1.8
52      */
53     public static void copyFile(File sourceFile, File targetFile) throws IOException {
54         BufferedInputStream inputStream = null;
55         BufferedOutputStream outputStream = null;
56         try {
57             inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
58             outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
59             byte[] b = new byte[BUFFER_SIZE];
60             int len;
61             while ((len = inputStream.read(b)) != -1) {
62                 outputStream.write(b, 0, len);
63             }
64             outputStream.flush();
65         } catch (Exception e) {
66             logger.error("copy file error", e);
67         } finally {
68             if (inputStream != null) {
69                 inputStream.close();
70             }
71             if (outputStream != null) {
72                 outputStream.close();
73             }
74         }
75     }
76
77     /**
78      * @param path
79      * @param fileType 文件类型,0 = 文件夹 1 = 文件
80      * @MethodName getAllFiles
81      * @Description 讀取文件夹下的,不包括子文件夹内
82      * @Author ChenJiaHe
83      * @Date 2019/9/17 15:56
84      * @Since JDK 1.8
85      */
86     public static List<String> getAllFiles(String path, String fileType) {
87         List<String> fileList = new ArrayList<>();
88         File fileDic = new File(path);
89         File[] files = fileDic.listFiles();
90         for (File file : files) {
91             if ("1".equals(fileType)) {
92                 if (file.isFile()) {
93                     fileList.add(file.toString());
94                 }
95             }
96             if ("0".equals(fileType)) {
97                 if (file.isDirectory()) {
98                     fileList.add(file.toString());
99                 }
100             }
101         }
102         return fileList;
103     }
104
105     /**
106      * @param path
107      * @MethodName getFolderFiles
108      * @Description 递归获取所有包括子文件夹的文件
109      * @Author ChenJiaHe
110      * @Date 2019/9/17 16:11
111      * @Since JDK 1.8
112      */
113     public static void getAllFileName(String path, List<String> listFileName) {
114         try {
115             File file = new File(path);
116             File[] files = file.listFiles();
117             String[] names = file.list();
118             if (names != null) {
119                 String[] completNames = new String[names.length];
120                 for (int i = 0; i < names.length; i++) {
121                     completNames[i] = path + names[i];
122                 }
123                 listFileName.addAll(Arrays.asList(completNames));
124             }
125             for (File a : files) {
126                 // 如果文件夹下有子文件夹,获取子文件夹下的所有文件全路径。
127                 if (a.isDirectory()) {
128                     getAllFileName(a.getAbsolutePath() + "\\", listFileName);
129                 }
130             }
131         } catch (Exception e) {
132             e.printStackTrace();
133         }
134     }
135
136     /**
137      * 读取文件内容,作为字符串返回
138      */
139     public static String readFileAsString(String filePath) throws IOException {
140         File file = new File(filePath);
141         if (!file.exists()) {
142             throw new FileNotFoundException(filePath);
143         }
144
145         if (file.length() > 1024 * 1024 * 1024) {
146             throw new IOException("File is too large");
147         }
148
149         StringBuilder sb = new StringBuilder((int) (file.length()));
150         // 创建字节输入流
151         FileInputStream fis = new FileInputStream(filePath);
152         // 创建一个长度为10240的Buffer
153         byte[] bbuf = new byte[10240];
154         // 用于保存实际读取的字节数
155         int hasRead = 0;
156         while ( (hasRead = fis.read(bbuf)) > 0 ) {
157             sb.append(new String(bbuf, 0, hasRead));
158         }
159         fis.close();
160         return sb.toString();
161     }
162
163     /**
164      * 根据文件路径读取byte[] 数组
165      */
166     public static byte[] readFileByBytes(String filePath) throws IOException {
167         File file = new File(filePath);
168         if (!file.exists()) {
169             throw new FileNotFoundException(filePath);
170         } else {
171             ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
172             BufferedInputStream in = null;
173
174             try {
175                 in = new BufferedInputStream(new FileInputStream(file));
176                 short bufSize = 1024;
177                 byte[] buffer = new byte[bufSize];
178                 int len1;
179                 while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
180                     bos.write(buffer, 0, len1);
181                 }
182
183                 byte[] var7 = bos.toByteArray();
184                 return var7;
185             } finally {
186                 try {
187                     if (in != null) {
188                         in.close();
189                     }
190                 } catch (IOException var14) {
191                     var14.printStackTrace();
192                 }
193
194                 bos.close();
195             }
196         }
197     }
198
199
200     /**
201      *  2020-06-29
202      *  cjh
203      * 图片格式判断
204      * */
205     public static boolean imageFormatJudge(MultipartFile firs) {
206         String imageName = firs.getOriginalFilename();
207         //截取格式
208         String suffix =imageName.substring(imageName.lastIndexOf(".") + 1);
209         //格式字母转小写
210         suffix = suffix.toLowerCase();
211         //进行判断
212         if(suffix.equals("png")) {
213             return true;
214         }else if(suffix.equals("jpg")){
215             return true;
216         }else if(suffix.equals("jpeg")){
217             return true;
218         }else {
219             return false;
220         }
221     }
222
96fdb9 223     /**
C 224      *  2020-06-29
225      *  cjh
226      * 图片格式判断
227      * */
228     public static boolean imageFormatJudge(File firs) {
229         String imageName = firs.getName();
230         //截取格式
231         String suffix =imageName.substring(imageName.lastIndexOf(".") + 1);
232         //格式字母转小写
233         suffix = suffix.toLowerCase();
234         //进行判断
235         if(suffix.equals("png")) {
236             return true;
237         }else if(suffix.equals("jpg")){
238             return true;
239         }else if(suffix.equals("jpeg")){
240             return true;
241         }else {
242             return false;
243         }
244     }
245
f0ed6f 246     /**视频上传的方法
C 247      * 保存到服务器里面的
248      * @param platformIconFile 视频文件
249      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
250      * @param saveFolder 保存到的文件夹,如:/bananer/
251      * @param autoDateFolder 是否生成日期文件夹
252      * @return 图片路径
253      * 2020-06-29 ChenJiaHe
254      */
255     public static String videoFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
256             ,boolean autoDateFolder) {
257         String fileName = "";
258         try {
259             if(platformIconFile == null) {
260                 throw new TipsException("请上传视频文件!");
261             }
262             if(!getMimeType(platformIconFile.getOriginalFilename())){
263                 throw new TipsException("请上传视频格式的文件!");
264             }
265
266             //设置图片大小
267             // String.format("%.1f",platformIconFile.getSize()/1024.0);
268             if(autoDateFolder){
269                 if(saveFolder.endsWith("/")){
270                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
271                 }else{
272                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
273                 }
274             }
275             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
276             if(unifiedFolder.endsWith("/")){
277                 if(saveFolder.startsWith("/")){
278                     saveFolder = saveFolder.replaceFirst("/","");
279                     unifiedFolder  = unifiedFolder + saveFolder;
280                 }else{
281                     unifiedFolder  = unifiedFolder+saveFolder;
282                 }
283             }else{
284                 if(saveFolder.startsWith("/")){
285                     unifiedFolder  = unifiedFolder + saveFolder;
286                 }else{
287                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
288                 }
289             }
290             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
291         } catch (RuntimeException e) {
292             e.printStackTrace();
293         }
294         return fileName;
295     }
296
5c5945 297     /**图片上传的方法
E 298      * 保存到服务器里面的
299      * @param platformIconFile 图片文件
300      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
301      * @param saveFolder 保存到的文件夹,如:/bananer/
302      * @param autoDateFolder 是否生成日期文件夹
303      * @return 图片路径
304      * 2020-06-29 ChenJiaHe
305      */
96fdb9 306     public static String handleFileUpload(File platformIconFile,String unifiedFolder,String saveFolder
C 307             ,boolean autoDateFolder) {
308         String fileName = "";
309         try {
310             if(platformIconFile == null) {
311                 throw new TipsException("请上传图片!");
312             }
313             if(!imageFormatJudge(platformIconFile)) {
314                 throw new TipsException("请上传png、jpg和jpeg格式的图片!");
315             }
316
317             //设置图片大小
318             // String.format("%.1f",platformIconFile.getSize()/1024.0);
319             if(autoDateFolder){
320                 if(saveFolder.endsWith("/")){
321                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
322                 }else{
323                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
324                 }
325             }
326             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
327             if(unifiedFolder.endsWith("/")){
328                 if(saveFolder.startsWith("/")){
329                     saveFolder = saveFolder.replaceFirst("/","");
330                     unifiedFolder  = unifiedFolder + saveFolder;
331                 }else{
332                     unifiedFolder  = unifiedFolder+saveFolder;
333                 }
334             }else{
335                 if(saveFolder.startsWith("/")){
336                     unifiedFolder  = unifiedFolder + saveFolder;
337                 }else{
338                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
339                 }
340             }
341             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
342         } catch (RuntimeException e) {
343             e.printStackTrace();
344         }
345         return fileName;
346     }
347
348     /**图片上传的方法
349      * 保存到服务器里面的
350      * @param platformIconFile 图片文件
351      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
352      * @param saveFolder 保存到的文件夹,如:/bananer/
353      * @param autoDateFolder 是否生成日期文件夹
354      * @return 图片路径
355      * 2020-06-29 ChenJiaHe
356      */
5c5945 357     public static String handleFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
E 358             ,boolean autoDateFolder) {
359         String fileName = "";
360         try {
361             if(platformIconFile == null) {
362                 throw new TipsException("请上传图片!");
363             }
364             if(!imageFormatJudge(platformIconFile)) {
365                 throw new TipsException("请上传png、jpg和jpeg格式的图片!");
366             }
367
368             //设置图片大小
96fdb9 369             // String.format("%.1f",platformIconFile.getSize()/1024.0);
5c5945 370             if(autoDateFolder){
E 371                 if(saveFolder.endsWith("/")){
372                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
373                 }else{
374                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
375                 }
376             }
377             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
378             if(unifiedFolder.endsWith("/")){
379                 if(saveFolder.startsWith("/")){
380                     saveFolder = saveFolder.replaceFirst("/","");
381                     unifiedFolder  = unifiedFolder + saveFolder;
382                 }else{
383                     unifiedFolder  = unifiedFolder+saveFolder;
384                 }
385             }else{
386                 if(saveFolder.startsWith("/")){
387                     unifiedFolder  = unifiedFolder + saveFolder;
388                 }else{
389                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
390                 }
391             }
392             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
393         } catch (RuntimeException e) {
394             e.printStackTrace();
395         }
396         return fileName;
397     }
398
399     /**
4f13f0 400      * 音频上传
E 401      * @param platformIconFile
402      * @param unifiedFolder
403      * @param saveFolder
404      * @param autoDateFolder
405      * @return
406      */
407     public static String handleAudioUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
408             ,boolean autoDateFolder) {
409         String fileName = "";
410         try {
411             if(platformIconFile == null) {
412                 throw new TipsException("请上传音频!");
413             }
414
415             if(autoDateFolder){
416                 if(saveFolder.endsWith("/")){
417                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
418                 }else{
419                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
420                 }
421             }
422
423             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
424             if(unifiedFolder.endsWith("/")){
425                 if(saveFolder.startsWith("/")){
426                     saveFolder = saveFolder.replaceFirst("/","");
427                     unifiedFolder  = unifiedFolder + saveFolder;
428                 }else{
429                     unifiedFolder  = unifiedFolder+saveFolder;
430                 }
431             }else{
432                 if(saveFolder.startsWith("/")){
433                     unifiedFolder  = unifiedFolder + saveFolder;
434                 }else{
435                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
436                 }
437             }
438             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
439         } catch (RuntimeException e) {
440             e.printStackTrace();
441         }
442         return fileName;
443     }
444
445     /**
f53873 446      * 文件上传
E 447      * @param platformIconFile
448      * @param unifiedFolder
449      * @param saveFolder
450      * @param autoDateFolder
451      * @return
452      */
453     public static String handleOtherFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
454             ,boolean autoDateFolder) {
455         String fileName = "";
456         try {
457             if(platformIconFile == null) {
458                 throw new TipsException("请上传文件!");
459             }
460
461             if(autoDateFolder){
462                 if(saveFolder.endsWith("/")){
463                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
464                 }else{
465                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
466                 }
467             }
468
469             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
470             if(unifiedFolder.endsWith("/")){
471                 if(saveFolder.startsWith("/")){
472                     saveFolder = saveFolder.replaceFirst("/","");
473                     unifiedFolder  = unifiedFolder + saveFolder;
474                 }else{
475                     unifiedFolder  = unifiedFolder+saveFolder;
476                 }
477             }else{
478                 if(saveFolder.startsWith("/")){
479                     unifiedFolder  = unifiedFolder + saveFolder;
480                 }else{
481                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
482                 }
483             }
484             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
485         } catch (RuntimeException e) {
486             e.printStackTrace();
487         }
488         return fileName;
489     }
490
491     /**
5c5945 492      * 2020-06-29 ChenJiaHe
96fdb9 493           * @param file             //文件对象
C 494           * @param filePath        //上传路径
495           * @param fileName        //文件名
496           * @return  文件名
497           */
5c5945 498     public static String fileUp(MultipartFile file, String filePath, String fileName){
E 499         String extName = ""; // 扩展名格式:
500         try {
501             if (file.getOriginalFilename().lastIndexOf(".") >= 0){
502                 extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
503             }
504             copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
505         } catch (IOException e) {
506             System.out.println(e);
507         }
508         return fileName+extName;
509     }
510
96fdb9 511
5c5945 512     /**
96fdb9 513      * 2020-06-29 ChenJiaHe
C 514           * @param file             //文件对象
515           * @param filePath        //上传路径
516           * @param fileName        //文件名
517           * @return  文件名
5c5945 518           */
96fdb9 519     public static String fileUp(File file, String filePath, String fileName){
C 520         String extName = ""; // 扩展名格式:
521         try {
522             if (file.getName().lastIndexOf(".") >= 0){
523                 extName = file.getName().substring(file.getName().lastIndexOf("."));
524             }
525             copyFile(file, filePath, fileName+extName).replaceAll("-", "");
526         } catch (IOException e) {
527             System.out.println(e);
528         }
529         return fileName+extName;
530     }
531
532     /**
533       * 写文件到当前目录的upload目录中
534       *
535       * @param in
536       * @param fileName
537       * @throws IOException
538       */
5c5945 539     private static String copyFile(InputStream in, String dir, String realName)throws IOException {
E 540         File file = new File(dir, realName);
541         file.setWritable(true);
542         if (!file.exists()) {
543             if (!file.getParentFile().exists()) {
544                 file.getParentFile().mkdirs();
545             }
546             file.createNewFile();
547         }
548         org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);
549         return realName;
550     }
551
552     /**
96fdb9 553           * 写文件到当前目录的upload目录中
C 554           *
555           * @param in
556           * @param fileName
557           * @throws IOException
558           */
559     private static String copyFile(File fileIn, String dir, String realName)throws IOException {
560         File file = new File(dir, realName);
561         file.setWritable(true);
562         if (!file.exists()) {
563             if (!file.getParentFile().exists()) {
564                 file.getParentFile().mkdirs();
565             }
566             file.createNewFile();
567         }
568         org.apache.commons.io.FileUtils.copyFile(fileIn,file);
569         return realName;
570     }
571
572     /**
5c5945 573      *
E 574      * @param date 时间
575      * @param format 时间格式
576      * @return 返回的时间格式字符串
577      */
578     public static String dateFormat(Date  date,String format) {
579         SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
580         return df.format(date);
581     }
582
583
584     /**
585      * @param stream 文件流
586      * @param saveUrl 保存到的文件夹
587      * @param fileName 文件图片
588      * @return
589      * @throws IOException
590      */
591     public static File inputStreamToFile(InputStream stream,String saveUrl,String fileName) throws IOException {
592         if(saveUrl.endsWith("/")){
593             saveUrl = saveUrl + fileName;
594         }else{
595             saveUrl = saveUrl +"/"+ fileName;
596         }
597         File targetFile = new File(saveUrl);
598         org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, targetFile);
599         return targetFile;
600     }
601
f0ed6f 602     /**判断是不是视频文件
C 603      * @param fileName 文件名称
604      * @return boolean true是视频文件
605      */
606     public static boolean getMimeType(String fileName) {
607         boolean b = false;
608         FileNameMap fileNameMap = URLConnection.getFileNameMap();
609         String type = fileNameMap.getContentTypeFor(fileName);
610         //是视频type是为空的
611         if(StringUtils.isEmpty(type)) {
612             b = true;
613         }
614         return b;
615     }
616
617     /**
618      * 判断是否为视频
619      * @param fileName
620      * @return
621      */
622     public static String isVideo(String fileName) {
623         FileNameMap fileNameMap = URLConnection.getFileNameMap();
624         String type = fileNameMap.getContentTypeFor(fileName);
625         return type;
626     }
627
628
5c5945 629 }