Appearance
Files
Starting from Java 7, the Files
utility class greatly simplifies file reading and writing.
Although Files
is part of the java.nio
package, it encapsulates many simple methods for file operations. For example, to read the entire content of a file as a byte[]
, you can write:
java
byte[] data = Files.readAllBytes(Path.of("/path/to/file.txt"));
For text files, you can read the entire content as a String
:
java
// Default UTF-8 encoding:
String content1 = Files.readString(Path.of("/path/to/file.txt"));
// Specify encoding:
String content2 = Files.readString(Path.of("/path", "to", "file.txt"), StandardCharsets.ISO_8859_1);
// Read line by line and return each line:
List<String> lines = Files.readAllLines(Path.of("/path/to/file.txt"));
Writing to files is also straightforward:
java
// Write binary data to a file:
byte[] data = ...;
Files.write(Path.of("/path/to/file.txt"), data);
// Write text with specified encoding:
Files.writeString(Path.of("/path/to/file.txt"), "文本内容...", StandardCharsets.ISO_8859_1);
// Write text line by line:
List<String> lines = ...;
Files.write(Path.of("/path/to/file.txt"), lines);
Additionally, the Files
utility class offers quick methods for file and directory operations, such as copy()
, delete()
, exists()
, and move()
.
A critical note is that the reading and writing methods provided by Files
are subject to memory limitations, making them suitable only for small files, such as configuration files. For large files, you should use file streams to read and write parts of the file at a time.
Summary
For simple small file read/write operations, the Files
utility class can simplify your code.