项目中,有时需要JAR包中被执行方法自身下载自己所在的JAR包。示例代码如下
String url_head = "http://localhost:8080"; //域名
// JAR 包所在路径
String url_path = url_head + this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
try {
File targetFile = new File("target.jar");
byte[] buffer = new byte[1024];
if (!file.exists()) {
int sum = 0;
int read = 0;
URL url = new URL(url_path);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((read = inputStream.read(buffer)) != -1) {
sum += read;
fileOutputStream.write(buffer, 0, read);
}
System.out.println("下载的JAR包大小为 " + sum);
}
} catch (Exception e) {
e.printStackTrace();
}