java - 搜索并列出 .m2(本地)maven 存储库

标签 java maven maven-3

对于一个项目,我想搜索本地 Maven 存储库 (.m2) 并列出 Artifact 。我怎样才能用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);
}

关于java - 搜索并列出 .m2(本地)maven 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58746591/

相关文章:

java - 如何在不打开android studio文件管理器的情况下从设备文件管理器的特定文件夹中获取文件?

java - IntelliJ IDEA + Play Framework——如何加速编译

java - Eclipse IDE J2SE-1.5 中的新 Maven 项目问题

java - 类未找到异常 : Failed to find data source: bigquery

java - 如何将第三方 jar 添加到本地 Maven 存储库?

eclipse - WebService - tomat/eclipse/maven - 请求的资源不可用

java - JarJar'ed artefact 和 Maven 部署过程

maven - 增加 IntelliJ java 堆大小

java - 在 Eclipse 中的 "mvn package"上运行 "Build project"

java - 在作为代理工作的 Nginx Ring 处理程序中读取服务器名称