FileUtils.java
6.73 KB
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
package cn.com.glsx.wechatbuild.util;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import javax.validation.constraints.NotBlank;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.UUID;
/**
* @author huangch
* @version V1.0
* @Title: FileUtils
* @Description:
* @Company: Didihu.com.cn
* @Date 2024/3/14 10:33
*/
@Slf4j
@UtilityClass
public class FileUtils {
/**
* 根据文件的URL读取文件内容
* @param fileUrl:
* @return java.lang.String
* @author huangch
* @date 2024/3/14 10:35
*/
public static String readFile(String fileUrl) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(new URL(fileUrl).openStream(), "UTF-8"));
StringBuilder contentBuilder = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
contentBuilder.append(line);
contentBuilder.append(System.lineSeparator());
}
return contentBuilder.toString().trim();
}
/**
* 获取文件到本地临时目录下
*
* @param fileUrl 文件url
* @return 文件路径,出现异常返回null
*/
public static String getFileToLocal(@NotBlank String fileUrl, @NotBlank String tempDir, @NotBlank String fileType) {
try {
Path directory = Paths.get(tempDir);
Files.createDirectories(directory);
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
log.error("Failed to connect. Response code: {}", connection.getResponseCode());
return null;
}
String fileName = UUID.randomUUID().toString();
String filePath = tempDir + File.separator + fileName + "." + fileType;
try (InputStream inputStream = new BufferedInputStream(connection.getInputStream());
OutputStream fileOutputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(filePath)))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
}
return filePath;
} catch (Exception e) {
log.error("Failed to get file from URL: {}", fileUrl, e);
return null;
}
}
/**
* 通过文件url获取文件Base64 编码的字符串
*
* @param fileUrl
* @return
*/
public String getFileAsBase64(String fileUrl) {
try {
URL url = new URL(fileUrl);
try (InputStream inputStream = url.openStream()) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byte[] fileBytes = byteArrayOutputStream.toByteArray();
return Base64.getEncoder().encodeToString(fileBytes);
}
} catch (IOException e) {
log.error("获取文件内容异常,error:{}", e.getMessage(), e);
return null;
}
}
/**
* 通过文件url获取文件内容字节数组
*
* @param fileUrl
* @return
*/
public byte[] getFileAsByteArr(String fileUrl) {
try {
URL url = new URL(fileUrl);
try (InputStream inputStream = url.openStream()) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
return byteArrayOutputStream.toByteArray();
}
} catch (IOException e) {
log.error("获取文件内容字节数组异常,error:{}", e.getMessage(), e);
return null;
}
}
/**
* 创建目录
*
* @param dirPath
* @return 创建目录成功 返回true,否则返回false
*/
public boolean makeDir(String dirPath) {
File dir = new File(dirPath);
if (!dir.exists()) {
return dir.mkdirs();
}
return true;
}
/**
* 移除本地临时文件
*
* @param filePath
* @return
*/
public boolean removeLocalFile(String filePath) {
try {
File tempFile = new File(filePath);
return tempFile.delete();
} catch (Exception e) {
log.error("Failed to remove local file: {}", filePath, e);
return false;
}
}
public static byte[] fileToByteArray(File file) {
// 检查文件是否存在
if (!file.exists()) {
log.error("File does not exist.");
return null;
}
// 创建一个字节数组输出流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (FileInputStream fileInputStream = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
// 循环读取文件内容到缓冲区,并写入到字节数组输出流
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
log.error("获取文件内容异常,error:{}", e.getMessage(), e);
return null;
}
// 获取字节数组输出流中的字节数组
return byteArrayOutputStream.toByteArray();
}
/**
* 计算文件大小
*
* @param fileData
* @return
*/
public String formatFileSize(byte[] fileData) {
if (fileData == null || fileData.length <= 0) {
return "0 B";
}
Double size = Double.valueOf(fileData.length);
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int index = 0;
while (size >= 1024 && index < units.length - 1) {
size /= 1024.0;
index++;
}
return String.format("%.2f %s", size, units[index]);
}
}