简体   繁体   English

将 JAR 文件从内部资源复制到临时文件夹

[英]Copy JAR file from inside resources to temp folder

I have in my Java project some JAR files that I need to copy in a temp folder of the filesystem.我的 Java 项目中有一些 JAR 文件,我需要将它们复制到文件系统的临时文件夹中。 However, once copied, all copied files are corrupt even their size is not the same as the original (when open zip with 7Zip appears an unformatted file instead of folders structure of jar).但是,一旦复制,所有复制的文件都会损坏,即使它们的大小与原始文件不同(当使用 7Zip 打开 zip 时会出现未格式化的文件,而不是 jar 的文件夹结构)。 I don't need those files for any process in my program like compiling, just for copy to the system.我的程序中的任何进程都不需要这些文件,比如编译,只是为了复制到系统。

I have tried some solutions like this , this , or with CommonsIO library, but always the files copied keep corrupt.我已经尝试过一些解决方案,例如thisthis或使用 CommonsIO 库,但复制的文件总是损坏。

EDIT: Some of the codes I've tried are编辑:我尝试过的一些代码是

InputStream source = getClass().getClassLoader().getResourceAsStream(originPath);
Files.copy(source, Paths.get(destPath), StandardCopyOption.REPLACE_EXISTING);
source.close();
byte[] source = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream(originPath));

File directoryFile = new File(originPath);
if(!directoryFile.exists()) {
  directoryFile.mkdirs();
}

try (FileOutputStream fileOutputStream = new FileOutputStream(destPath)){
  fileOutputStream.write(source);
}
catch (Exception exception) {
  throw new IOException(String.format("Failed to copy the file %s", sourceName));
}

How can I do that?我怎样才能做到这一点?

Have you tried:你有没有尝试过:

Path source = Paths.get(...)
Path dest   = Paths.get(...)
Files.move(source,dest);

Another way:另一种方式:

File source  = new File("....");
File dest    = new File("...");
file.renameTo(dest);

Basically you need to address the file in a filesystem and not in the classpath of the existing application, hence I see no point in using getClass().getResourceAsStream()基本上,您需要在文件系统中而不是在现有应用程序的类路径中处理文件,因此我认为使用getClass().getResourceAsStream()没有意义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM