|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+package com.chinaitop.mq.utils;
|
|
|
2
|
+
|
|
|
3
|
+import java.io.ByteArrayOutputStream;
|
|
|
4
|
+import java.io.File;
|
|
|
5
|
+import java.io.FileInputStream;
|
|
|
6
|
+import java.io.FileNotFoundException;
|
|
|
7
|
+import java.io.IOException;
|
|
|
8
|
+import java.util.Base64;
|
|
|
9
|
+
|
|
|
10
|
+import cn.hutool.http.HttpUtil;
|
|
|
11
|
+
|
|
|
12
|
+public class FileUtil {
|
|
|
13
|
+ /**
|
|
|
14
|
+ * 根据文件路径将文件转为二进制数组
|
|
|
15
|
+ * @param filePath:文件路径
|
|
|
16
|
+ * @return
|
|
|
17
|
+ */
|
|
|
18
|
+ public static byte[] file2byte(String filePath) {
|
|
|
19
|
+ byte[] buffer = null;
|
|
|
20
|
+ try {
|
|
|
21
|
+ File file = new File(filePath);
|
|
|
22
|
+ FileInputStream fis = new FileInputStream(file);
|
|
|
23
|
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
|
|
24
|
+ byte[] b = new byte[1024];
|
|
|
25
|
+ int n;
|
|
|
26
|
+ while ((n = fis.read(b)) != -1) {
|
|
|
27
|
+ bos.write(b, 0, n);
|
|
|
28
|
+ }
|
|
|
29
|
+ fis.close();
|
|
|
30
|
+ bos.close();
|
|
|
31
|
+ buffer = bos.toByteArray();
|
|
|
32
|
+ } catch (FileNotFoundException e) {
|
|
|
33
|
+ e.printStackTrace();
|
|
|
34
|
+ } catch (IOException e) {
|
|
|
35
|
+ e.printStackTrace();
|
|
|
36
|
+ }
|
|
|
37
|
+ return buffer;
|
|
|
38
|
+ }
|
|
|
39
|
+
|
|
|
40
|
+ /**
|
|
|
41
|
+ * 将二进制数组转为字符串
|
|
|
42
|
+ * @param byteArray
|
|
|
43
|
+ * @return
|
|
|
44
|
+ */
|
|
|
45
|
+ public static String toHexString(byte[] byteArray) {
|
|
|
46
|
+ if (byteArray == null || byteArray.length < 1)
|
|
|
47
|
+ throw new IllegalArgumentException(
|
|
|
48
|
+ "this byteArray must not be null or empty");
|
|
|
49
|
+
|
|
|
50
|
+ final StringBuilder hexString = new StringBuilder();
|
|
|
51
|
+ for (int i = 0; i < byteArray.length; i++) {
|
|
|
52
|
+ if ((byteArray[i] & 0xff) < 0x10)// 0~F前面不零
|
|
|
53
|
+ hexString.append("0");
|
|
|
54
|
+ hexString.append(Integer.toHexString(0xFF & byteArray[i]));
|
|
|
55
|
+ }
|
|
|
56
|
+ return hexString.toString().toLowerCase();
|
|
|
57
|
+ }
|
|
|
58
|
+
|
|
|
59
|
+
|
|
|
60
|
+ /**
|
|
|
61
|
+ * 网络文件转文件流
|
|
|
62
|
+ */
|
|
|
63
|
+ public static byte[] urlToStream(String url) {
|
|
|
64
|
+ return HttpUtil.downloadBytes(url);
|
|
|
65
|
+ }
|
|
|
66
|
+
|
|
|
67
|
+ /**
|
|
|
68
|
+ * 获取Base64编码的字符串
|
|
|
69
|
+ *
|
|
|
70
|
+ * @param url 网络文件地址
|
|
|
71
|
+ * @methodName: getBase64Content
|
|
|
72
|
+ * @return: java.lang.String 网络文件地址
|
|
|
73
|
+ * @author: ybw
|
|
|
74
|
+ * @date: 2024/7/19
|
|
|
75
|
+ **/
|
|
|
76
|
+ public static String getBase64Content(String url) {
|
|
|
77
|
+ byte[] bytes = urlToStream(url);
|
|
|
78
|
+ // 将文件内容转换为Base64字符串
|
|
|
79
|
+ return Base64.getEncoder().encodeToString(bytes);
|
|
|
80
|
+ }
|
|
|
81
|
+}
|