0
# File and I/O Operations
1
2
File operations, stream handling, resource management, and NIO utilities through FileUtil and IoUtil classes.
3
4
## Capabilities
5
6
### File Reading Operations
7
8
Read file contents in various formats and encodings.
9
10
```java { .api }
11
/**
12
* Read file content as UTF-8 string
13
* @param file the file to read
14
* @return file content as string
15
* @throws IORuntimeException if reading fails
16
*/
17
public static String readUtf8String(File file);
18
19
/**
20
* Read file content as string with specified charset
21
* @param file the file to read
22
* @param charset charset to use for reading
23
* @return file content as string
24
* @throws IORuntimeException if reading fails
25
*/
26
public static String readString(File file, Charset charset);
27
28
/**
29
* Read file content as byte array
30
* @param file the file to read
31
* @return file content as bytes
32
* @throws IORuntimeException if reading fails
33
*/
34
public static byte[] readBytes(File file);
35
36
/**
37
* Read file lines as list
38
* @param file the file to read
39
* @param charset charset to use for reading
40
* @return list of lines
41
* @throws IORuntimeException if reading fails
42
*/
43
public static List<String> readLines(File file, Charset charset);
44
45
/**
46
* Read file lines as UTF-8 list
47
* @param file the file to read
48
* @return list of lines in UTF-8
49
* @throws IORuntimeException if reading fails
50
*/
51
public static List<String> readUtf8Lines(File file);
52
```
53
54
**Usage Examples:**
55
56
```java
57
import cn.hutool.core.io.FileUtil;
58
import java.io.File;
59
import java.nio.charset.StandardCharsets;
60
61
File textFile = new File("example.txt");
62
63
// Read file content
64
String content = FileUtil.readUtf8String(textFile);
65
String gbkContent = FileUtil.readString(textFile, Charset.forName("GBK"));
66
byte[] bytes = FileUtil.readBytes(textFile);
67
68
// Read lines
69
List<String> lines = FileUtil.readUtf8Lines(textFile);
70
List<String> gbkLines = FileUtil.readLines(textFile, Charset.forName("GBK"));
71
```
72
73
### File Writing Operations
74
75
Write content to files in various formats and encodings.
76
77
```java { .api }
78
/**
79
* Write string content to file using UTF-8 encoding
80
* @param content content to write
81
* @param file target file
82
* @return target file
83
* @throws IORuntimeException if writing fails
84
*/
85
public static File writeUtf8String(String content, File file);
86
87
/**
88
* Write string content to file using specified charset
89
* @param content content to write
90
* @param file target file
91
* @param charset charset to use for writing
92
* @return target file
93
* @throws IORuntimeException if writing fails
94
*/
95
public static File writeString(String content, File file, Charset charset);
96
97
/**
98
* Write byte array to file
99
* @param data bytes to write
100
* @param file target file
101
* @return target file
102
* @throws IORuntimeException if writing fails
103
*/
104
public static File writeBytes(byte[] data, File file);
105
106
/**
107
* Append string content to file using UTF-8 encoding
108
* @param content content to append
109
* @param file target file
110
* @return target file
111
* @throws IORuntimeException if writing fails
112
*/
113
public static File appendUtf8String(String content, File file);
114
115
/**
116
* Write lines to file
117
* @param lines lines to write
118
* @param file target file
119
* @param charset charset to use
120
* @return target file
121
* @throws IORuntimeException if writing fails
122
*/
123
public static File writeLines(Collection<String> lines, File file, Charset charset);
124
```
125
126
### File System Operations
127
128
Perform file system operations like copying, moving, and deleting.
129
130
```java { .api }
131
/**
132
* Copy file or directory
133
* @param src source file or directory
134
* @param dest destination file or directory
135
* @param isOverride whether to override existing files
136
* @return destination file
137
* @throws IORuntimeException if copying fails
138
*/
139
public static File copy(File src, File dest, boolean isOverride);
140
141
/**
142
* Copy file content only (not directory structure)
143
* @param src source file
144
* @param dest destination file
145
* @param isOverride whether to override existing file
146
* @return destination file
147
* @throws IORuntimeException if copying fails
148
*/
149
public static File copyContent(File src, File dest, boolean isOverride);
150
151
/**
152
* Move file or directory
153
* @param src source file or directory
154
* @param dest destination file or directory
155
* @param isOverride whether to override existing files
156
* @return destination file
157
* @throws IORuntimeException if moving fails
158
*/
159
public static File move(File src, File dest, boolean isOverride);
160
161
/**
162
* Delete file or directory recursively
163
* @param file file or directory to delete
164
* @return true if deletion successful
165
*/
166
public static boolean del(File file);
167
168
/**
169
* Create directory and parent directories if not exist
170
* @param dir directory to create
171
* @return created directory
172
*/
173
public static File mkdir(File dir);
174
175
/**
176
* Create file and parent directories if not exist
177
* @param file file to create
178
* @return created file
179
* @throws IORuntimeException if creation fails
180
*/
181
public static File touch(File file);
182
```
183
184
### File Properties and Validation
185
186
Check file properties and validate file operations.
187
188
```java { .api }
189
/**
190
* Check if file or directory exists
191
* @param path file path
192
* @return true if exists
193
*/
194
public static boolean exist(String path);
195
196
/**
197
* Check if file or directory exists
198
* @param file file object
199
* @return true if exists
200
*/
201
public static boolean exist(File file);
202
203
/**
204
* Check if path represents a file (not directory)
205
* @param file file object
206
* @return true if is file
207
*/
208
public static boolean isFile(File file);
209
210
/**
211
* Check if path represents a directory
212
* @param file file object
213
* @return true if is directory
214
*/
215
public static boolean isDirectory(File file);
216
217
/**
218
* Get file size in bytes
219
* @param file file object
220
* @return file size in bytes, -1 if file doesn't exist
221
*/
222
public static long size(File file);
223
224
/**
225
* Get file extension
226
* @param file file object
227
* @return file extension without dot, null if no extension
228
*/
229
public static String extName(File file);
230
231
/**
232
* Get file name without extension
233
* @param file file object
234
* @return file name without extension
235
*/
236
public static String mainName(File file);
237
```
238
239
### Stream Operations (IoUtil)
240
241
Handle input/output streams with automatic resource management.
242
243
```java { .api }
244
/**
245
* Copy data from input stream to output stream
246
* @param in input stream
247
* @param out output stream
248
* @return number of bytes copied
249
* @throws IORuntimeException if copying fails
250
*/
251
public static long copy(InputStream in, OutputStream out);
252
253
/**
254
* Copy data with specified buffer size
255
* @param in input stream
256
* @param out output stream
257
* @param bufferSize buffer size for copying
258
* @return number of bytes copied
259
* @throws IORuntimeException if copying fails
260
*/
261
public static long copy(InputStream in, OutputStream out, int bufferSize);
262
263
/**
264
* Read input stream content as string
265
* @param in input stream
266
* @param charset charset to use for reading
267
* @return content as string
268
* @throws IORuntimeException if reading fails
269
*/
270
public static String read(InputStream in, Charset charset);
271
272
/**
273
* Read input stream content as UTF-8 string
274
* @param in input stream
275
* @return content as UTF-8 string
276
* @throws IORuntimeException if reading fails
277
*/
278
public static String readUtf8(InputStream in);
279
280
/**
281
* Read input stream content as byte array
282
* @param in input stream
283
* @return content as bytes
284
* @throws IORuntimeException if reading fails
285
*/
286
public static byte[] readBytes(InputStream in);
287
288
/**
289
* Close closeable resource safely (no exception thrown)
290
* @param closeable resource to close
291
*/
292
public static void close(Closeable closeable);
293
294
/**
295
* Close multiple closeable resources safely
296
* @param closeables resources to close
297
*/
298
public static void close(Closeable... closeables);
299
```
300
301
**Usage Examples:**
302
303
```java
304
import cn.hutool.core.io.FileUtil;
305
import cn.hutool.core.io.IoUtil;
306
import java.io.*;
307
308
// File operations
309
File sourceFile = new File("source.txt");
310
File destFile = new File("destination.txt");
311
312
// Writing
313
FileUtil.writeUtf8String("Hello World", destFile);
314
FileUtil.appendUtf8String("\nNew line", destFile);
315
316
// Copying
317
FileUtil.copy(sourceFile, destFile, true); // Override if exists
318
319
// File properties
320
boolean exists = FileUtil.exist("example.txt");
321
long size = FileUtil.size(new File("example.txt"));
322
String extension = FileUtil.extName(new File("example.txt")); // "txt"
323
324
// Stream operations
325
try (InputStream in = new FileInputStream("input.txt");
326
OutputStream out = new FileOutputStream("output.txt")) {
327
328
long copied = IoUtil.copy(in, out);
329
System.out.println("Copied " + copied + " bytes");
330
}
331
332
// Safe resource closing
333
FileInputStream fis = null;
334
try {
335
fis = new FileInputStream("file.txt");
336
String content = IoUtil.readUtf8(fis);
337
} finally {
338
IoUtil.close(fis); // Safe close, no exception thrown
339
}
340
```
341
342
### NIO Operations (NioUtil)
343
344
Modern NIO-based file operations for better performance.
345
346
```java { .api }
347
/**
348
* Copy file using NIO
349
* @param src source file path
350
* @param dest destination file path
351
* @return destination path
352
* @throws IORuntimeException if copying fails
353
*/
354
public static Path copy(Path src, Path dest);
355
356
/**
357
* Move file using NIO
358
* @param src source file path
359
* @param dest destination file path
360
* @return destination path
361
* @throws IORuntimeException if moving fails
362
*/
363
public static Path move(Path src, Path dest);
364
365
/**
366
* Delete file or directory using NIO
367
* @param path path to delete
368
* @return true if deletion successful
369
*/
370
public static boolean del(Path path);
371
372
/**
373
* Read file content using NIO
374
* @param path file path
375
* @return file content as string
376
* @throws IORuntimeException if reading fails
377
*/
378
public static String readUtf8(Path path);
379
380
/**
381
* Write content to file using NIO
382
* @param path file path
383
* @param content content to write
384
* @return file path
385
* @throws IORuntimeException if writing fails
386
*/
387
public static Path writeUtf8(Path path, String content);
388
```
389
390
### Resource Operations (ResourceUtil)
391
392
Handle classpath resources and resource loading.
393
394
```java { .api }
395
/**
396
* Get resource URL from classpath
397
* @param resource resource path
398
* @return resource URL, null if not found
399
*/
400
public static URL getResource(String resource);
401
402
/**
403
* Get resource as stream from classpath
404
* @param resource resource path
405
* @return resource stream, null if not found
406
*/
407
public static InputStream getResourceAsStream(String resource);
408
409
/**
410
* Read resource content as UTF-8 string
411
* @param resource resource path
412
* @return resource content
413
* @throws IORuntimeException if reading fails
414
*/
415
public static String readUtf8Str(String resource);
416
417
/**
418
* Read resource content as string with specified charset
419
* @param resource resource path
420
* @param charset charset to use
421
* @return resource content
422
* @throws IORuntimeException if reading fails
423
*/
424
public static String readStr(String resource, Charset charset);
425
```
426
427
### File Type Detection (FileTypeUtil)
428
429
Detect file types based on file headers and content.
430
431
```java { .api }
432
/**
433
* Get file type based on file header
434
* @param file file to check
435
* @return file type string (e.g., "jpg", "png", "pdf")
436
*/
437
public static String getType(File file);
438
439
/**
440
* Get file type based on input stream header
441
* @param in input stream
442
* @return file type string
443
*/
444
public static String getType(InputStream in);
445
446
/**
447
* Check if file is of specified type
448
* @param file file to check
449
* @param type expected file type
450
* @return true if file matches type
451
*/
452
public static boolean isType(File file, String type);
453
```
454
455
**Usage Examples:**
456
457
```java
458
// Resource operations
459
String config = ResourceUtil.readUtf8Str("config/application.properties");
460
InputStream stream = ResourceUtil.getResourceAsStream("data/template.xml");
461
462
// File type detection
463
String fileType = FileTypeUtil.getType(new File("image.jpg")); // "jpg"
464
boolean isPdf = FileTypeUtil.isType(new File("document.pdf"), "pdf");
465
466
// NIO operations
467
Path source = Paths.get("source.txt");
468
Path dest = Paths.get("destination.txt");
469
NioUtil.copy(source, dest);
470
String content = NioUtil.readUtf8(source);
471
```
472
473
## Exception Handling
474
475
File and I/O operations use IORuntimeException for consistent error handling:
476
477
```java { .api }
478
public class IORuntimeException extends RuntimeException {
479
public IORuntimeException(String message);
480
public IORuntimeException(String message, Throwable cause);
481
public IORuntimeException(Throwable cause);
482
}
483
```