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