0

Possible Duplicate:
Copying files from one directory to another in Java

I have a folder (c:/InstallationFiles) with .jar files in it. i want to read through it and if the name equals test1 i want to copy it to a test1 folder, then if the name is test2 copy it to a test2 folder etc. this is what i have so far:

private static int copyJARFiles() {

    resultCode = 0;

    File installFolder = new File(Constants.WINDOWS + Constants.INSTALLATION_FOLDER);
    File[] installFiles = installFolder.listFiles();

    for (int i = 0; i < installFiles.length; i++) {
        if (installFiles[i].equals("test1.jar")){

        }
        if (installFiles[i].equals("test2.jar")){

        }
    }
    return resultCode;
}

not sure how to copy it then. im still a rookie.

thank you / kind regards

Community
  • 1
  • 1
user1759247
  • 101
  • 1
  • 5
  • 8

2 Answers2

0

if you want to copy jar: You can use apache IO api. Use the below code: FileUtils.copy(sourceFile,destinationFile);

You can also use java 7. It contains direct function to copy files.

if you want extract jar: You can use java.util.zip.*; package classes.

Please let me know if you need more explanation.

  • for (int i = 0; i < installFiles.length; i++) { if (installFiles[i].toString().contains("test1.jar")) { Path source = Paths.get("C:/Dir/test1.jar"); Path target = Paths.get("c:/test1/test1.jar"); Files.copy(source, target); } return resultCode; Will something like this work? thank you for the help. much appreciated – user1759247 Dec 18 '12 at 09:59
  • yes, but you have to use Java 7. – Rahul Gakhar Dec 18 '12 at 10:58
  • for (int i = 0; i < installFiles.length; i++) { if (installFiles[i].toString().contains("test1.jar")) { Path source = Paths.get(**installFiles[i].getPath()**); Path target = Paths.get("c:/test1/test1.jar"); Files.copy(source, target); } You have mistake in source file path. Please replace as in bold – Rahul Gakhar Dec 18 '12 at 11:02
  • If you find my answer helpful, Please like my answer. – Rahul Gakhar Dec 18 '12 at 11:04
0

Not sure I fully understood your task but maybe this example will help you

for (File f : installFolder.listFiles()) {
    if (f.getName().endsWith(".jar")) {
        File targetDir = new File(installFolder, f.getName().replace(".jar", ""));
        if (!targetDir.exists()) {
            targetDir.mkdir();
        }
        File target = new File(targetDir, f.getName());
        Files.copy(f.toPath(), target.toPath());
    }
}

The main idea is that Java 7 provides us with Files.copy util

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275