Java Files的常用方法都有哪些?
在Java中,java.nio.file.Files
类提供了许多用于操作文件和目录的静态方法。以下是一些常用的方法,以及相应的代码示例:
1. 读取文件内容:
-
readAllLines(Path path, Charset cs)
: 读取文件的所有行。Path filePath = Paths.get("example.txt"); List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
-
readAllBytes(Path path)
: 读取文件的所有字节。Path filePath = Paths.get("example.txt"); byte[] fileBytes = Files.readAllBytes(filePath);
2. 写入文件内容:
-
write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options)
: 将字符串写入文件。Path filePath = Paths.get("output.txt"); List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3"); Files.write(filePath, content, StandardCharsets.UTF_8);
-
write(Path path, byte[] bytes, OpenOption... options)
: 将字节数组写入文件。Path filePath = Paths.get("output.txt"); byte[] contentBytes = "Hello, World!".getBytes(StandardCharsets.UTF_8); Files.write(filePath, contentBytes);
3. 复制和移动文件:
-
copy(Path source, Path target, CopyOption... options)
: 复制文件。Path sourcePath = Paths.get("source.txt"); Path targetPath = Paths.get("target.txt"); Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
-
move(Path source, Path target, CopyOption... options)
: 移动文件。Path sourcePath = Paths.get("source.txt"); Path targetPath = Paths.get("target.txt"); Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
4. 删除文件和目录:
-
delete(Path path)
: 删除文件或目录。Path filePath = Paths.get("example.txt"); Files.delete(filePath);
-
deleteIfExists(Path path)
: 如果存在,则删除文件或目录。Path filePath = Paths.get("example.txt"); Files.deleteIfExists(filePath);
5. 检查文件和目录属性:
-
isDirectory(Path path, LinkOption... options)
: 判断给定路径是否为目录。Path dirPath = Paths.get("example_directory"); boolean isDirectory = Files.isDirectory(dirPath);
-
isRegularFile(Path path, LinkOption... options)
: 判断给定路径是否为普通文件。Path filePath = Paths.get("example.txt"); boolean isRegularFile = Files.isRegularFile(filePath);
6. 获取文件和目录信息:
-
exists(Path path, LinkOption... options)
: 判断给定路径是否存在。Path filePath = Paths.get("example.txt"); boolean exists = Files.exists(filePath);
-
size(Path path)
: 获取文件的大小。Path filePath = Paths.get("example.txt"); long fileSize = Files.size(filePath);
这些只是 java.nio.file.Files
类的一部分常用方法。根据具体需求,可以选择合适的方法进行文件和目录操作。