0

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?

Angel F.
  • 176
  • 1
  • 16
  • 1
    How is maven related to this? Are you trying to do that from maven's plugin or something? Or its your application that in runtime tries to access the temp folder and copy from there? Please share the code snippet of what you've tried because the links you've mentioned are about copying from within a jar itself, and it doesn't seem to be your case... – Mark Bramnik Jul 14 '20 at 05:52
  • Can you share the code snippet that you used to copy the files? – Bala Jul 14 '20 at 07:18
  • I've edited the post. Deleted the Maven tag as I think is not related, but my code is under a Maven project. – Angel F. Jul 14 '20 at 11:59
  • Are the JAR files included with your class files when you run? Why put the files in jar files and not just have the contents that will get bundled in a jar file. – matt Jul 14 '20 at 12:11
  • The first example works for me. Something is wrong with your environment. – matt Jul 14 '20 at 13:28

1 Answers1

0

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

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • It sounds like their bundling the jar files in with their resources. In which case these would not be applicable. – matt Jul 14 '20 at 13:11
  • @matt I thought that the question is about copying the file from the application folder (on filesystem) to some other folder... I might be wrong so. OP, please refine the question and show an example of what exactly do you try to copy – Mark Bramnik Jul 14 '20 at 13:21