如何在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”。我的替代品有什么问题
# 1 楼答案
相对化
有Path relativize(Path other)
示例
输出
# 2 楼答案
你需要相对化你的路径。另一方面:Java8引入了
Files.find
方法,这将大大简化collectFileList
方法