13693261870
2024-07-16 8f4d51938689a5ce77ca839b802f1c150faf8f2c
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
package com.se.simu.helper;
 
import com.twmacinta.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
 
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.List;
 
/**
 * 文件帮助类
 * 
 * @author WWW
 * @date 2024-07-16
 */
@Slf4j
public class FileHelper {
    public final static String POINT = ".";
 
    public final static int I16 = 16;
 
    public static final double D1024 = 1024.0;
 
    public static final double D1050 = 1050.0;
 
    public final static int I1000000 = 1000000;
 
    public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
    /**
     * 获取文件名
     */
    public static String getFileName(String file) {
        int idx = file.lastIndexOf(File.separator);
        if (idx > -1) {
            return file.substring(idx + 1);
        }
 
        return "";
    }
 
    /**
     * 获取文件名称
     */
    public static String getName(String file) {
        String fileName = getFileName(file);
        int idx = fileName.lastIndexOf(".");
        if (idx > -1) {
            return fileName.substring(0, idx);
        }
 
        return fileName;
    }
 
    /**
     * 获取文件扩展名
     */
    public static String getExtension(File file) {
        if (file == null) {
            return null;
        }
 
        String fileName = file.getName().toLowerCase();
 
        int idx = fileName.indexOf(POINT);
        if (idx == -1) {
            return "";
        }
 
        return fileName.substring(idx);
    }
 
    /**
     * 获取文件扩展名
     */
    public static String getExtension(String fileName) {
        if (StringHelper.isEmpty(fileName)) {
            return "";
        }
 
        int idx = fileName.lastIndexOf(POINT);
        if (idx == -1) {
            return "";
        }
 
        return fileName.substring(idx).toLowerCase();
    }
 
    /**
     * 获取多用途互联网邮件扩展类型
     */
    public static String getMime(String ext) {
        switch (ext) {
            // 图片
            case ".tif":
            case ".tiff":
                return "image/tiff";
            case ".img":
                return "application/x-img";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            // 音/视频
            case ".mp3":
                return "audio/mp3";
            case ".mp4":
                return "video/mpeg4";
            case ".avi":
                return "video/avi";
            case ".mpg":
            case ".mpeg":
                return "video/mpg";
            case ".wav":
                return "audio/wav";
            case ".wma":
                return "audio/x-ms-wma";
            case ".swf":
                return "application/x-shockwave-flash";
            case ".wmv":
                return "video/x-ms-wmv";
            case ".rm":
                return "application/vnd.rn-realmedia";
            case ".rmvb":
                return "application/vnd.rn-realmedia-vbr";
            // 网页
            case ".js":
                return "application/x-javascript";
            case ".css":
                return "text/css";
            case ".asp":
                return "text/asp";
            case ".mht":
                return "message/rfc822";
            case ".jsp":
            case ".htm":
            case ".html":
            case ".xhtml":
                return "text/html";
            case ".xml":
            case ".svg":
                return "text/xml";
            // 文件
            case ".txt":
                return "text/plain";
            case ".dbf":
                return "application/x-dbf";
            case ".mdb":
                return "application/msaccess";
            case ".pdf":
                return "application/pdf";
            case ".ppt":
            case ".pptx":
                return "application/x-ppt";
            case ".doc":
            case ".docx":
                return "application/msword";
            case ".xls":
            case ".xlsx":
                return "application/vnd.ms-excel";
            case ".dgn":
                return "application/x-dgn";
            case ".dwg":
                return "application/x-dwg";
            case ".ext":
                return "application/x-msdownload";
            // 默认
            default:
                return "application/octet-stream";
        }
    }
 
    /**
     * 字节单位换算
     */
    public static String formatByte(long byteNumber) {
        double kbNumber = byteNumber / D1024;
        if (kbNumber < D1024) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / D1024;
        if (mbNumber < D1024) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / D1024;
        if (gbNumber < D1024) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / D1024;
 
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
 
    /**
     * 获取平方米
     */
    public static String getSquareMeter(double num) {
        if (num < I1000000) {
            return new DecimalFormat("#.##平方米").format(num);
        }
 
        double knum = num / I1000000;
 
        return new DecimalFormat("#.##平方千米").format(knum);
    }
 
    /**
     * byte转MB
     */
    public static double sizeToMb(long size) {
        if (size < D1050) {
            return 0.001;
        }
 
        String str = String.format("%.3f", size / D1024 / D1024);
 
        return Double.parseDouble(str);
    }
 
    /**
     * 3.获取文件MD5码(JDK)
     */
    public static String getMd5ByJdk(String filePath) throws IOException {
        FileInputStream fileStream = new FileInputStream(filePath);
        String md5 = DigestUtils.md5Hex(fileStream);
        fileStream.close();
 
        return md5;
    }
 
    /**
     * 2.获取快速 MD5 码
     */
    public static String getFastMd5(String filePath) throws IOException {
        String hash = MD5.asHex(MD5.getHash(new File(filePath)));
 
        MD5 md5 = new MD5();
        md5.Update(hash, null);
 
        return md5.asHex();
    }
 
    /**
     * 删除文件夹
     *
     * @param dir 文件夹
     */
    public static void deleteDir(String dir) {
        File file = new File(dir);
 
        deleteFiles(file);
    }
 
    /**
     * 级联删除文件
     *
     * @param file 文件
     */
    public static void deleteFiles(File file) {
        if (null == file || !file.exists()) {
            return;
        }
 
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        deleteFiles(f);
                    } else {
                        f.delete();
                    }
                }
            }
        }
 
        file.delete();
    }
 
    /**
     * 获取相对路径
     *
     * @param file 文件
     * @return 相对路径
     */
    public static String getRelativePath(String file) {
        if (StringHelper.isEmpty(file)) {
            return null;
        }
 
        int idx = file.lastIndexOf(File.separator);
        int start = file.lastIndexOf(File.separator, idx - 1);
 
        return file.substring(start + 1);
    }
 
    /**
     * 获取路径
     *
     * @param file 文件
     * @return 文件路径
     */
    public static String getPath(String file) {
        if (StringHelper.isEmpty(file)) {
            return null;
        }
 
        int end = file.lastIndexOf(File.separator);
 
        return file.substring(0, end);
    }
 
    /**
     * 1.获取文件的MD5
     */
    @SuppressWarnings("unused")
    public static String getFileMd5(String filePath) {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
 
            fis = new FileInputStream(new File(filePath));
            FileChannel fChannel = fis.getChannel();
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024);
 
            while (fChannel.read(buffer) != -1) {
                buffer.flip();
                md.update(buffer);
                buffer.compact();
            }
            byte[] b = md.digest();
 
            return byteToHexString(b);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 
    /**
     * 字节码转16进制
     */
    public static String byteToHexString(byte[] tmp) {
        // 每个字节用 16 进制表示的话,使用两个字符,
        char[] str = new char[16 * 2];
 
        // 所以表示成 16 进制需要 32 个字符,表示转换结果中对应的字符位置
        int k = 0;
        // 从第一个字节开始,对 MD5 的每一个字节
        for (int i = 0; i < I16; i++) {
            // 转换成 16 进制字符的转换
            byte byte0 = tmp[i];
            // 取字节中高 4 位的数字转换
            str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
            // >>> 为逻辑右移,将符号位一起右移, 取字节中低 4 位的数字转换
            str[k++] = HEX_DIGITS[byte0 & 0xf];
        }
        // 换后的结果转换为字符串
        return new String(str);
    }
 
    /**
     * 获取字符串的MD5码
     */
    public static String getStringMd5(String text) {
        StringBuilder builder = new StringBuilder();
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
 
            byte[] bytes = md5.digest(text.getBytes(StandardCharsets.UTF_8));
            for (byte aByte : bytes) {
                builder.append(Integer.toHexString((0x000000FF & aByte) | 0xFFFFFF00).substring(6));
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
 
        return builder.toString();
    }
 
    /**
     * 根据路径获取文件
     */
    public static void getFilesByPath(List<String> list, String path) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null == files) {
                return;
            }
 
            for (File f : files) {
                if (f.isDirectory()) {
                    getFilesByPath(list, f.getPath());
                } else {
                    list.add(f.getPath());
                }
            }
        } else {
            list.add(file.getPath());
        }
    }
 
    /**
     * 复制文件
     *
     * @param src  源文件
     * @param dest 目录文件
     */
    public static void copyFile(File src, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(src);
            os = new FileOutputStream(dest);
 
            byte[] buffer = new byte[1024];
 
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            os.close();
            is.close();
        }
    }
}