通常、私が使用するファイルの名前を変更するには:
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.
これを行うには、ファイルを抽出してから、名前を変更するファイルの名前を変更する必要があります。
一度に 1 つのエントリを 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();
}
}