文件通常重命名我使用一个文件:的Java:重命名里面一个.jar
File oldFile = new File("file path");
oldFile.renameTo(new File("file path with new name"));
但是如果我要重命名的文件是一个可执行的.jar里面是有办法,从将其重命名那里?
文件通常重命名我使用一个文件:的Java:重命名里面一个.jar
File oldFile = new File("file path");
oldFile.renameTo(new File("file path with new name"));
但是如果我要重命名的文件是一个可执行的.jar里面是有办法,从将其重命名那里?
不,你不能这样做,除非你提取JAR文件,重命名文件并重新打包它。
你不能这样做。因为
A jar file is not itself a file system and the contents cannot be accessed
using File objects.
为此 拳,你必须提取该文件,然后重命名要重命名的文件。
您可以一次复制一个jar,一个条目,重命名您想要更改的条目。这可能比开箱,重命名和重新打包更高效。
如果不更改对该名称的所有引用,则不能重命名类文件。在不重新编译所有代码的情况下,可以使用像ObjectWebs ASM这样的库来检查字节代码并更改对该类的引用。如果该类在字符串中被引用,那么您也可以更改该字符串。
是的,你可以重命名一个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();
}
}
这听起来很疯狂。你有什么背景知道为什么你需要这样做? – 2012-07-26 11:55:34
我有点困惑,你的意思是在相同的.jar文件中重命名.jar文件? – 2012-07-26 11:57:57
有鉴于此,WinZip和WinRar能够在不提取/重新压缩的情况下执行此操作,因此从技术上讲我相信它是可行的。标准API(ZipFile,ZipEntry)似乎不支持它。 – aioobe 2012-07-26 12:01:04