简体   繁体   中英

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. 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). 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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