Попытка отредактировать файл свойств в jar из файла ear. Лучший способ сделать это?
Я имею в виду использование TrueZip API в Java для манипулирования с файлом ear
- извлечь ухо в каталог tmp,
- затем искать через банки в TMP,
- если найдены свойства в банке,
- затем распакуйте его в tmp,
- изменить это свойство
- затем упакуйте его обратно в банку,
- затем упакуйте банку обратно в ухо.
ИЛИ есть ли лучший способ использования сценария оболочки?
Пожалуйста, порекомендуйте.
Спасибо
2 ответа
Используя TrueZIP 7, вы можете использовать что-то вроде этого:
public static void main(String args[]) throws IOException {
// Remember to add the following dependencies to the class path:
// Compile time artifactId(s): truezip-file
// Run time artifactId(s): truezip-kernel, truezip-driver-file, truezip-driver-zip
TFile.setDefaultArchiveDetector(new TDefaultArchiveDetector("ear|jar|war"));
search(new TFile(args[0])); // e.g. "my.ear"
TFile.umount(); // commit changes
}
private void search(TFile entry) throws IOException {
if (entry.isDirectory()) {
for (TFile member : dir.listFiles())
search(member);
} else if (entry.isFile()) {
if (entry.getName().endsWith(".properties");
update(entry);
} // else is special file or non-existent
}
private void update(TFile file) throws IOException {
Properties properties = new Properties();
InputStream in = new TFileInputStream(file);
try {
properties.load(in);
} finally {
in.close();
}
// [your updates here]
OutputStream out = new TFileOutputStream(file);
try {
properties.store(out, "updated");
} finally {
out.close();
}
}
Я использовал ответ @Christian Schlichtherle, чтобы начать с того, что я пытался достичь, но использование True Zip изменилось совсем немного. Я думал, что опубликую то, что мне нужно было сделать, чтобы помочь кому-то.
Вам нужно создать класс, который расширяет TApplication. В моем случае я делаю его абстрактным, чтобы я мог повторно использовать установочный код в моих классах реализации логики.
Application.java:
import de.schlichtherle.truezip.file.TApplication;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TConfig;
import de.schlichtherle.truezip.fs.archive.zip.JarDriver;
import de.schlichtherle.truezip.fs.archive.zip.ZipDriver;
import de.schlichtherle.truezip.socket.sl.IOPoolLocator;
/**
* An abstract class which configures the TrueZIP Path module.
*/
abstract class Application<E extends Exception> extends TApplication<E> {
/**
* Runs the setup phase.
* <p>
* This method is {@link #run run} only once at the start of the life
* cycle.
*/
@Override
protected void setup() {
TConfig.get().setArchiveDetector(
new TArchiveDetector(
TArchiveDetector.NULL,
new Object[][] {
{ "zip", new ZipDriver(IOPoolLocator.SINGLETON)},
{ "ear|jar|war", new JarDriver(IOPoolLocator.SINGLETON)},
}));
}
}
Затем вы просто расширяете абстрактный класс и реализуете метод "работа", как показано.
ChangeProperty.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.ServiceConfigurationError;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileInputStream;
import de.schlichtherle.truezip.file.TFileOutputStream;
public class ChangeProperty extends Application<IOException> {
public static void main(String args[]) throws IOException {
try {
System.exit(new ChangeProperty().run(args));
} catch (ServiceConfigurationError e) {
// Ignore this error because what we wanted to accomplish has been done.
}
}
private void search(TFile entry) throws IOException {
System.out.println("Scanning: " + entry);
if (entry.isDirectory()) {
for (TFile member : entry.listFiles())
search(member);
} else if (entry.isFile()) {
if (entry.getName().endsWith(".properties")) {
update(entry);
}
}
}
private void update(TFile file) throws IOException {
System.out.println("Updating: " + file);
Properties properties = new Properties();
InputStream in = new TFileInputStream(file);
try {
properties.load(in);
} finally {
in.close();
}
// [your updates here]
// For example: properties.setProperty(key, newValue);
OutputStream out = new TFileOutputStream(file);
try {
properties.store(out, "updated by loggerlevelchanger");
} finally {
out.close();
}
}
@Override
protected int work(String[] args) throws IOException {
search(new TFile(args[0]));
return 0;
}
}