How to delete a specific file / folder from jar pragmatically in java

How to delete a specific file / folder from jar pragmatically in java.

I have a jar ABC.jar contains files, folders and other jars of say child.jar. Under child.jar, I want to delete a specific file. How can i do so my ABC.jar structure remains the same.

Any help would be appreciated.

Thanks at Advance.

+4
source share
5 answers

As @icza replied, we have to iterate through the original jar file and delete the record we don't want. Here is the Java code that you can reference.

 public static void main(String[] args) throws IOException {


  String jarName = args[0];
  String fileName = args[1];

  // Create file descriptors for the jar and a temp jar.

  File jarFile = new File(jarName);
  File tempJarFile = new File(jarName + ".tmp");

  // Open the jar file.

  JarFile jar = new JarFile(jarFile);
  System.out.println(jarName + " opened.");

  // Initialize a flag that will indicate that the jar was updated.

  boolean jarUpdated = false;

  try {
     // Create a temp jar file with no manifest. (The manifest will
     // be copied when the entries are copied.)

     Manifest jarManifest = jar.getManifest();
     JarOutputStream tempJar =
        new JarOutputStream(new FileOutputStream(tempJarFile));

     // Allocate a buffer for reading entry data.

     byte[] buffer = new byte[1024];
     int bytesRead;

     try {
        // Open the given file.

        FileInputStream file = new FileInputStream(fileName);

        try {
           // Create a jar entry and add it to the temp jar.

           JarEntry entry = new JarEntry(fileName);
           tempJar.putNextEntry(entry);

           // Read the file and write it to the jar.

           while ((bytesRead = file.read(buffer)) != -1) {
              tempJar.write(buffer, 0, bytesRead);
           }

           System.out.println(entry.getName() + " added.");
        }
        finally {
           file.close();
        }

        // Loop through the jar entries and add them to the temp jar,
        // skipping the entry that was added to the temp jar already.

        for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {
           // Get the next entry.

           JarEntry entry = (JarEntry) entries.nextElement();

           // If the entry has not been added already, add it.

           if (! entry.getName().equals(fileName)) {
              // Get an input stream for the entry.

              InputStream entryStream = jar.getInputStream(entry);

              // Read the entry and write it to the temp jar.

              tempJar.putNextEntry(entry);

              while ((bytesRead = entryStream.read(buffer)) != -1) {
                 tempJar.write(buffer, 0, bytesRead);
              }
           }
        }

        jarUpdated = true;
     }
     catch (Exception ex) {
        System.out.println(ex);

        // Add a stub entry here, so that the jar will close without an
        // exception.

        tempJar.putNextEntry(new JarEntry("stub"));
     }
     finally {
        tempJar.close();
     }
  }
  finally {
     jar.close();
     System.out.println(jarName + " closed.");

     // If the jar was not updated, delete the temp jar file.

     if (! jarUpdated) {
        tempJarFile.delete();
     }
  }

  // If the jar was updated, delete the original jar file and rename the
  // temp jar file to the original name.

  if (jarUpdated) {
     jarFile.delete();
     tempJarFile.renameTo(jarFile);
     System.out.println(jarName + " updated.");
  }

}

+1
source

Jar / zip files are not editable. You cannot delete the entry from the jar / zip file.

, "" jar : jar, jar jar, .


​​ ( Java lib , ZipFile, ZipInputStream, JarFile, JarInputStream):

jar/zip . ( ). . , , , ( ), ( ) (, / ).


Java, , zip -d.

0

Sun/Oracle , java-api.

0

JAR, . :

Runtime.getRuntime().exec("zip -d path\my.jar some_file.txt");

- jar, some_file.txt - , . . , ,

jar, , , :

String path = SomeClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();

, :

    Process p = Runtime.getRuntime().exec("zip -d path\my.jar some_file.txt");
    BufferedReader reader = 
            new BufferedReader(new InputStreamReader(p.getInputStream()));

       String line = "";    
       StringBuilder sb = new StringBuilder();
       while ((line = reader.readLine())!= null) {
           sb.append(line + "\n");
           System.out.println(line);
       }
       System.out.println(sb.toString());
0
    public static void filterJar(Path jarInFileName, String skipRegex, Path jarOutFileName) throws IOException {
        ZipEntry entry;
        ZipInputStream zis = null;
        JarOutputStream os = null;
        FileInputStream is = null;
        try {
            is = new FileInputStream(jarInFileName.toFile());
            Pattern pattern = Pattern.compile(skipRegex);
            zis = new ZipInputStream(is);
            os = new JarOutputStream(new FileOutputStream(jarOutFileName.toFile())); 
            while ((entry = zis.getNextEntry()) != null) {
                if (pattern.matcher(entry.getName()).matches()) continue;
                os.putNextEntry(entry);
                if (!entry.isDirectory()) {
                    byte[] bytes = toBytes(zis);
                    os.write(bytes);
                }
            }
        }
        catch (Exception ex) {
           throw new IOException("unable to filter jar:" + ex.getMessage());
        }
        finally {
            closeQuietly(is);
            closeQuietly(os);
        }
    }
    public static void closeQuietly(final Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        }
        catch (final Exception e) {}
    }
    public static byte[] toBytes(InputStream aInput) throws IOException {
        byte[] bucket = new byte[5 * 1024];
        ByteArrayOutputStream result = null;
        result = new ByteArrayOutputStream(bucket.length);
        int bytesRead = 0;
        while (bytesRead != -1) {
            bytesRead = aInput.read(bucket);
            if (bytesRead > 0) {
                result.write(bucket, 0, bytesRead);
            }
        }
        return result.toByteArray();
    }

public static void main(String[] args) throws IOException {
  filterJar(Paths.get("./old.jar"), "BOOT-INF/lib.*", Paths.get("./new.jar"));
}
0

All Articles