ChenJiaHe
2021-01-21 38914a6947d4cb76577fa97432d810ec66a870fe
提交 | 用户 | 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
f0ed6f 223     /**视频上传的方法
C 224      * 保存到服务器里面的
225      * @param platformIconFile 视频文件
226      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
227      * @param saveFolder 保存到的文件夹,如:/bananer/
228      * @param autoDateFolder 是否生成日期文件夹
229      * @return 图片路径
230      * 2020-06-29 ChenJiaHe
231      */
232     public static String videoFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
233             ,boolean autoDateFolder) {
234         String fileName = "";
235         try {
236             if(platformIconFile == null) {
237                 throw new TipsException("请上传视频文件!");
238             }
239             if(!getMimeType(platformIconFile.getOriginalFilename())){
240                 throw new TipsException("请上传视频格式的文件!");
241             }
242
243             //设置图片大小
244             // String.format("%.1f",platformIconFile.getSize()/1024.0);
245             if(autoDateFolder){
246                 if(saveFolder.endsWith("/")){
247                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
248                 }else{
249                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
250                 }
251             }
252             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
253             if(unifiedFolder.endsWith("/")){
254                 if(saveFolder.startsWith("/")){
255                     saveFolder = saveFolder.replaceFirst("/","");
256                     unifiedFolder  = unifiedFolder + saveFolder;
257                 }else{
258                     unifiedFolder  = unifiedFolder+saveFolder;
259                 }
260             }else{
261                 if(saveFolder.startsWith("/")){
262                     unifiedFolder  = unifiedFolder + saveFolder;
263                 }else{
264                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
265                 }
266             }
267             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
268         } catch (RuntimeException e) {
269             e.printStackTrace();
270         }
271         return fileName;
272     }
273
5c5945 274     /**图片上传的方法
E 275      * 保存到服务器里面的
276      * @param platformIconFile 图片文件
277      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
278      * @param saveFolder 保存到的文件夹,如:/bananer/
279      * @param autoDateFolder 是否生成日期文件夹
280      * @return 图片路径
281      * 2020-06-29 ChenJiaHe
282      */
283     public static String handleFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
284             ,boolean autoDateFolder) {
285         String fileName = "";
286         try {
287             if(platformIconFile == null) {
288                 throw new TipsException("请上传图片!");
289             }
290             if(!imageFormatJudge(platformIconFile)) {
291                 throw new TipsException("请上传png、jpg和jpeg格式的图片!");
292             }
293
294             //设置图片大小
295            // String.format("%.1f",platformIconFile.getSize()/1024.0);
296             if(autoDateFolder){
297                 if(saveFolder.endsWith("/")){
298                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
299                 }else{
300                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
301                 }
302             }
303             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
304             if(unifiedFolder.endsWith("/")){
305                 if(saveFolder.startsWith("/")){
306                     saveFolder = saveFolder.replaceFirst("/","");
307                     unifiedFolder  = unifiedFolder + saveFolder;
308                 }else{
309                     unifiedFolder  = unifiedFolder+saveFolder;
310                 }
311             }else{
312                 if(saveFolder.startsWith("/")){
313                     unifiedFolder  = unifiedFolder + saveFolder;
314                 }else{
315                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
316                 }
317             }
318             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
319         } catch (RuntimeException e) {
320             e.printStackTrace();
321         }
322         return fileName;
323     }
324
325     /**
4f13f0 326      * 音频上传
E 327      * @param platformIconFile
328      * @param unifiedFolder
329      * @param saveFolder
330      * @param autoDateFolder
331      * @return
332      */
333     public static String handleAudioUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
334             ,boolean autoDateFolder) {
335         String fileName = "";
336         try {
337             if(platformIconFile == null) {
338                 throw new TipsException("请上传音频!");
339             }
340
341             if(autoDateFolder){
342                 if(saveFolder.endsWith("/")){
343                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
344                 }else{
345                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
346                 }
347             }
348
349             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
350             if(unifiedFolder.endsWith("/")){
351                 if(saveFolder.startsWith("/")){
352                     saveFolder = saveFolder.replaceFirst("/","");
353                     unifiedFolder  = unifiedFolder + saveFolder;
354                 }else{
355                     unifiedFolder  = unifiedFolder+saveFolder;
356                 }
357             }else{
358                 if(saveFolder.startsWith("/")){
359                     unifiedFolder  = unifiedFolder + saveFolder;
360                 }else{
361                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
362                 }
363             }
364             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
365         } catch (RuntimeException e) {
366             e.printStackTrace();
367         }
368         return fileName;
369     }
370
371     /**
f53873 372      * 文件上传
E 373      * @param platformIconFile
374      * @param unifiedFolder
375      * @param saveFolder
376      * @param autoDateFolder
377      * @return
378      */
379     public static String handleOtherFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
380             ,boolean autoDateFolder) {
381         String fileName = "";
382         try {
383             if(platformIconFile == null) {
384                 throw new TipsException("请上传文件!");
385             }
386
387             if(autoDateFolder){
388                 if(saveFolder.endsWith("/")){
389                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
390                 }else{
391                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
392                 }
393             }
394
395             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
396             if(unifiedFolder.endsWith("/")){
397                 if(saveFolder.startsWith("/")){
398                     saveFolder = saveFolder.replaceFirst("/","");
399                     unifiedFolder  = unifiedFolder + saveFolder;
400                 }else{
401                     unifiedFolder  = unifiedFolder+saveFolder;
402                 }
403             }else{
404                 if(saveFolder.startsWith("/")){
405                     unifiedFolder  = unifiedFolder + saveFolder;
406                 }else{
407                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
408                 }
409             }
410             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
411         } catch (RuntimeException e) {
412             e.printStackTrace();
413         }
414         return fileName;
415     }
416
417     /**
5c5945 418      * 2020-06-29 ChenJiaHe
E 419      * @param file             //文件对象
420      * @param filePath        //上传路径
421      * @param fileName        //文件名
422      * @return  文件名
423      */
424     public static String fileUp(MultipartFile file, String filePath, String fileName){
425         String extName = ""; // 扩展名格式:
426         try {
427             if (file.getOriginalFilename().lastIndexOf(".") >= 0){
428                 extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
429             }
430             copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
431         } catch (IOException e) {
432             System.out.println(e);
433         }
434         return fileName+extName;
435     }
436
437     /**
438           * 写文件到当前目录的upload目录中
439           *
440           * @param in
441           * @param fileName
442           * @throws IOException
443           */
444     private static String copyFile(InputStream in, String dir, String realName)throws IOException {
445         File file = new File(dir, realName);
446         file.setWritable(true);
447         if (!file.exists()) {
448             if (!file.getParentFile().exists()) {
449                 file.getParentFile().mkdirs();
450             }
451             file.createNewFile();
452         }
453         org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);
454         return realName;
455     }
456
457     /**
458      *
459      * @param date 时间
460      * @param format 时间格式
461      * @return 返回的时间格式字符串
462      */
463     public static String dateFormat(Date  date,String format) {
464         SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
465         return df.format(date);
466     }
467
468
469     /**
470      * @param stream 文件流
471      * @param saveUrl 保存到的文件夹
472      * @param fileName 文件图片
473      * @return
474      * @throws IOException
475      */
476     public static File inputStreamToFile(InputStream stream,String saveUrl,String fileName) throws IOException {
477         if(saveUrl.endsWith("/")){
478             saveUrl = saveUrl + fileName;
479         }else{
480             saveUrl = saveUrl +"/"+ fileName;
481         }
482         File targetFile = new File(saveUrl);
483         org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, targetFile);
484         return targetFile;
485     }
486
f0ed6f 487     /**判断是不是视频文件
C 488      * @param fileName 文件名称
489      * @return boolean true是视频文件
490      */
491     public static boolean getMimeType(String fileName) {
492         boolean b = false;
493         FileNameMap fileNameMap = URLConnection.getFileNameMap();
494         String type = fileNameMap.getContentTypeFor(fileName);
495         //是视频type是为空的
496         if(StringUtils.isEmpty(type)) {
497             b = true;
498         }
499         return b;
500     }
501
502     /**
503      * 判断是否为视频
504      * @param fileName
505      * @return
506      */
507     public static String isVideo(String fileName) {
508         FileNameMap fileNameMap = URLConnection.getFileNameMap();
509         String type = fileNameMap.getContentTypeFor(fileName);
510         return type;
511     }
512
513
5c5945 514 }