Java:重命名.jar中的文件

时间:2012-07-26 11:53:38

标签: java file jar

通常要重命名我使用的文件:

File oldFile = new File("file path");
oldFile.renameTo(new File("file path with new name"));

但是,如果我要重命名的文件在.jar可执行文件中,有什么办法可以从那里重命名它?

4 个答案:

答案 0 :(得分:2)

不,除非您解压缩JAR文件,重命名文件并重新打包,否则不能这样做。

答案 1 :(得分:2)

你不能这样做。因为

A jar file is not itself a file system and the contents cannot be accessed
using File objects.

要做到这一点 您必须解压缩文件,然后重命名要重命名的文件。

答案 2 :(得分:1)

您可以复制一个jar,一次一个条目,重命名您要更改的条目。这可能比解包,重命名和重新打包更有效。

如果不更改对该名称的所有引用,则无法重命名类文件。无需重新编译所有代码,您可以使用像ObjectWebs ASM这样的库来检查字节代码并更改对该类的引用。如果在String中引用了类,您可能也想要更改字符串。

答案 3 :(得分:0)

是的,您可以在jar中重命名文件。例如,您可以使用JarEntryFilter

像这样:

...
import org.springframework.boot.loader.jar.JarEntryData;
import org.springframework.boot.loader.jar.JarEntryFilter;
import org.springframework.boot.loader.jar.JarFile;
import org.springframework.boot.loader.tools.JarWriter;
import org.springframework.boot.loader.util.AsciiBytes;
...
    JarWriter writer = new JarWriter(destination);
    try {
        JarFile filteredJarFile = sourceJar.getFilteredJarFile(new JarEntryFilter() {
            @Override
            public AsciiBytes apply(AsciiBytes name, JarEntryData entryData) {
                String string = name.toString();
                String exp = "^a.*";
                if (string.matches(exp)) {
                    string = string.replaceFirst(exp, "replaced");
                    return new AsciiBytes(string);
                }
                return name;
            }
        });
        writer.writeEntries(filteredJarFile);
    } finally {
        try {
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }