[英]How to create the relative path in Java?
我有根目錄和嵌套在根目錄中的文件(它們可以在子目錄中)。 我想創建這些文件的相對路徑列表。 我寫了代碼,但替換不起作用。
public class FileManager {
private Path rootPath;
private List<Path> fileList = new ArrayList<Path>();
public FileManager(Path rootPath) throws IOException{
this.rootPath = rootPath;
collectFileList(rootPath);
}
private void collectFileList(Path path) throws IOException{
if (Files.isRegularFile(path)){
if (!fileList.contains(path.getParent())){
String result_path = path.toAbsolutePath().toString().replaceAll(rootPath.toString(),"");
fileList.add(Paths.get(result_path));
}
}else if (Files.isDirectory(path)){
for (File file:path.toFile().listFiles()
) {
collectFileList(Paths.get(file.getAbsolutePath()));
}
}
}
例如:我有根目錄“E:\test”,我有文件“E:\test\test2\1.txt”。 我想替換路徑文件的根目錄,並返回“test2\1.txt”。 但我總是收到“E:\test\test2\1.txt”。 我的替換有什么問題?
相對化!
相對化是分辨率的倒數。 此方法嘗試構造一個相對路徑,當針對此路徑解析時,會生成一個與給定路徑定位相同文件的路徑。 例如,在 UNIX 上,如果此路徑為“/a/b”且給定路徑為“/a/b/c/d”,則生成的相對路徑將為“c/d”。 如果該路徑和給定路徑沒有根組件,則可以構造相對路徑。 如果只有一個路徑具有根組件,則無法構造相對路徑。 如果兩個路徑都有一個根組件,那么是否可以構造相對路徑取決於實現。 如果此路徑和給定路徑相等,則返回空路徑。
對於任意兩條歸一化路徑 p 和 q,其中 q 沒有根分量,
p.relativize(p.resolve(q)).equals(q) 如果支持符號鏈接,那么當針對該路徑解析時,生成的路徑是否產生可用於定位與其他文件相同的文件的路徑是實現依賴。 例如,如果此路徑是“/a/b”並且給定路徑是“/a/x”,那么生成的相對路徑可能是“../x”。 如果“b”是符號鏈接,那么如果“a/b/../x”將定位與“/a/x”相同的文件,則取決於實現。
例子
Path dir = Path.of("/var/lib");
Path file = Path.of("/var/lib/someapp/1.txt");
Path relative = dir.relativize(file);
System.out.print(relative);
Output
someapp/1.txt
你需要相對化你的路徑。 旁注:java 8 引入了Files.find
方法,這將大大簡化您的collectFileList
方法。
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
public class FileManager {
private final Path rootPath;
private final List<Path> fileList;
public FileManager(Path rootPath) throws IOException{
this.rootPath = rootPath;
this.fileList = collectFileList(rootPath);
}
private static List<Path> collectFileList(Path path) throws IOException {
try (Stream<Path> pathStream = Files.find(
path,
Integer.MAX_VALUE,
(file, attrs) -> attrs.isRegularFile()
)) {
return pathStream
.map(path::relativize)
.collect(toList());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.