1. 基本概念
1.1 什么是Files工具类?
Files是java.nio.file包下的一个实用工具类,用于操作文件和目录。它提供了一系列静态方法,使得文件和目录的操作更加简单和高效。
2. 常用方法解析
2.1 创建文件和目录
Path filePath = Paths.get("example.txt");
try {
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
上述代码使用Files.createFile()方法创建了一个名为"example.txt"的文件。
2.2 复制文件
Path sourcePath = Paths.get("source.txt");
Path targetPath = Paths.get("target.txt");
try {
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
使用Files.copy()方法可以将一个文件复制到另一个地方,第三个参数指定了复制选项,如
StandardCopyOption.REPLACE_EXISTING表示如果目标文件已存在则覆盖。
2.3 移动文件
Path sourcePath = Paths.get("source.txt");
Path targetPath = Paths.get("target.txt");
try {
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
Files.move()方法用于将文件从一个位置移动到另一个位置,同样可以使用复制选项。
2.4 删除文件
Path filePath = Paths.get("example.txt");
try {
Files.delete(filePath);
} catch (IOException e) {
e.printStackTrace();
}
使用Files.delete()方法可以删除指定的文件。
2.5 读取文件内容
Path filePath = Paths.get("example.txt");
try {
List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
Files.readAllLines()方法用于读取文件的所有行,返回一个List<String>,每个元素代表文件的一行。
注:这个方法要考虑文件大小和内存的情况。
2.6 写入文件内容
Path filePath = Paths.get("example.txt");
List<String> content = Arrays.asList("Hello", "World");
try {
Files.write(filePath, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
Files.write()方法可以将字符串列表写入文件,创建一个新文件或者覆盖已存在的文件。
3. Files方法总览
方法 | 描述 |
createFile | 创建文件 |
createDirectory | 创建目录 |
copy | 复制文件或目录 |
move | 移动文件或目录 |
delete | 删除文件或目录 |
readAllLines | 读取文件的所有行 |
write | 将字符串列表写入文件 |
isRegularFile | 判断路径是否为常规文件 |
isDirectory | 判断路径是否为目录 |
exists | 判断路径是否存在 |
isReadable / isWritable | 判断文件或目录是否可读/可写 |
size | 获取文件的大小 |
newBufferedReader | 创建一个BufferedReader以读取文件 |
newBufferedWriter | 创建一个BufferedWriter以写入文件 |
newInputStream | 创建一个InputStream以从文件读取字节 |
newOutputStream | 创建一个OutputStream以向文件写入字节 |