如果不使用Maven从Maven仓库下载构件,可以使用Java代码手动下载构件并添加到项目中。以下是一个示例代码:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class MavenArtifactDownloader {
public static void main(String[] args) {
String groupId = "com.example";
String artifactId = "my-library";
String version = "1.0.0";
String repositoryUrl = "https://repo.maven.apache.org/maven2/";
String artifactUrl = repositoryUrl + groupId.replace(".", "/") + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar";
try {
downloadArtifact(artifactUrl, artifactId + "-" + version + ".jar");
System.out.println("Artifact downloaded successfully.");
} catch (IOException e) {
System.out.println("Failed to download artifact: " + e.getMessage());
}
}
private static void downloadArtifact(String artifactUrl, String fileName) throws IOException {
URL url = new URL(artifactUrl);
BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
in.close();
}
}
在上面的代码中,我们指定了要下载的构件的groupId、artifactId和version。然后,我们构建了构件在Maven仓库中的URL,并使用downloadArtifact()
方法下载构件。下载的构件将保存为当前目录下的文件artifactId-version.jar
。
请注意,上述示例直接从Maven中央仓库下载构件。如果您要下载的构件位于其他Maven仓库中,您需要提供该仓库的URL,并相应地构建构件的URL。