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