在Java中,使用文件路径的最佳方法是使用java.nio.file.Path
类。这个类提供了一种简单、可扩展的方式来操作文件路径。以下是一些关键概念和示例:
Path path = Paths.get("path", "to", "file.txt");
Path fileName = path.getFileName();
Path directory = path.getParent();
Path relativePath = Paths.get("path", "to", "file.txt");
Path absolutePath = relativePath.toAbsolutePath();
boolean exists = Files.exists(path);
List<String> lines = Files.readAllLines(path);
Files.write(path, "Hello, world!".getBytes());
try (Stream<Path> paths = Files.walk(Paths.get("path", "to", "directory"))) {
paths.forEach(System.out::println);
}
Files.createDirectory(path);
Files.delete(path);
Files.copy(sourcePath, targetPath);
Files.move(sourcePath, targetPath);
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
WatchService watchService = FileSystems.getDefault().newWatchService();
Path directoryToWatch = Paths.get("path", "to", "directory");
directoryToWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("File changed: " + event.context());
}
key.reset();
}
使用java.nio.file.Path
类可以更方便地处理文件路径,并且可以利用Java 8中引入的Stream API来简化很多文件操作。
领取专属 10元无门槛券
手把手带您无忧上云