我有一个托管在云中的 jar 文件。我的要求是我想将该 jar 提取到我的本地计算机中。我已经编写了一个代码来将 jar 提取到我的本地计算机中。但是它需要找到 jar在我的本地机器中。似乎我浪费了机器空间,因为我所做的是从给定的 URL 输入流创建一个 jar。(将 jar 文件复制到我的本地机器中(物理文件可以在我的机器中找到))
url = new URL("https://myres/jarFile.jar");
InputStream in = new BufferedInputStream(url.openStream());
java.nio.file.Files.copy(in,"temp.jar");
我的要求是,我不这样做,如何从 URL 输入流中提取 jar 文件到我的机器中。然后不需要将 URL jar 物理复制到我的机器中。只包含提取的 jar 文件。
提取 jar 的代码
public String extractJar(String input){
Path dirPath = Paths.get("location for file to be copy");
JarFile jar;
URL url;
try {
url = new URL(input);
InputStream in = new BufferedInputStream(url.openStream());
java.nio.file.Files.copy(in, dirPath.resolve("temp.jar"));//I want to skip this step
jar = new JarFile(dirPath.resolve("temp.jar").toString());
Enumeration<JarEntry> enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
JarEntry file = enumEntries.nextElement();
File f = new File(dirPath + File.separator + file.getName());
// Check if file is a Dir
if (file.isDirectory()) {
f.mkdirs();
continue;
}
InputStream is = jar.getInputStream(file);
FileOutputStream fos = new FileOutputStream(f);
// Write contents
while (is.available() > 0) {
fos.write(is.read());
}
fos.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new ResourceNotFoundException(e.getMessage());
}
return dirPath.toAbsolutePath().toString();
}
最佳答案
试试这个:
public static void extractAllEntries(String urlPath, String destination) {
try {
byte[] buffer = new byte[1024];
InputStream input = new URL(urlPath).openStream();
JarInputStream jin = new JarInputStream(input);
ZipEntry entry;
while ((entry = jin.getNextEntry()) != null) {
ZipEntry file = (ZipEntry) entry;
File f = new java.io.File(destination + java.io.File.separator
+ file.getName());
if (file.isDirectory()) {
f.mkdir();
continue;
}
FileOutputStream fos = new FileOutputStream(f);
int len;
while ((len = jin.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
jin.closeEntry();
jin.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我只是粗略地编码了..请正确处理finally子句中输入流的关闭。
关于java - 如何从 URL 中提取 jar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650181/