对于一个项目,我想搜索本地Maven存储库(.m2)并列出工件。我如何用Java做到这一点?我找到了https://github.com/apache/maven-indexer,并检查了是否可以使用它列出我的本地Maven存储库。但是仍然无法解决。如果您对我可以使用的简单库有任何想法,请提出建议?
先谢谢了。 !
对于一个项目,我想搜索本地Maven存储库(.m2)并列出工件。我如何用Java做到这一点?我找到了https://github.com/apache/maven-indexer,并检查了是否可以使用它列出我的本地Maven存储库。但是仍然无法解决。如果您对我可以使用的简单库有任何想法,请提出建议?
先谢谢了。 !
考虑使用Files.walkFileTree(Path start,FileVisitor<? super Path> visitor)
class MyM2Visitor extends SimpleFileVisitor<Path> {
private final Path root;
public MyM2Visitor(Path root) {
this.root = root;
}
//implement rest as necessary
}
//later...
//Current user's .m2 directory:
Path m2 = Path.of(System.getProperty("user.home"),".m2");
MyM2Visitor visitor = new MyM2Visitor(m2);
try {
Files.walkFileTree(m2,visitor);
} catch(IOException e) {
e.printStackTrace();
}
另请参阅:SimpleFilevisitor JavaDoc
您应该自定义访问者,以便在遇到目录或文件时采取适当的措施,例如:
@Override
public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) throws IOException {
logger.trace("File: {}",file);
int count = file.getNameCount();
Path versionPath = file.getParent();
String versionAsString = versionPath.getFileName();
//or:
versionAsString = file.getName(count-2).toString();
String artifactId = file.getName(count-3).toString();
Path groupIdPath = file.getParent().getParent().getParent();
Path relativeToM2 = root.relativize(groupIdPath);
String groupId = relativeToM2.toString().replace(File.separatorChar,'.');
//do other things
return super.visitFile(file,attrs);
}