WAR 存档中的 Java 编辑文件
•浏览 1
Java edit file inside WAR archive
我一直在论坛上阅读有关如何读取/编辑存档中的文件,但仍然无法得到我的答案。主要使用getResourceAsStream,并且必须在其类路径中。
我需要做的是,使用给定的文件路径作为输入读取和更新 xml 文件,然后将其重新部署到 Tomcat。
但是到目前为止,我仍然无法回答如何使用给定的完整路径作为输入来编辑 WAR 存档中的 AAR 文件中的 xml 文件。有人可以帮帮我吗?
例如,我想编辑 applicationContext.xml 文件:
C:/webapp.WAR
来自 webapp.WAR 文件:
webapp.WAR/WEB-INF/services/myapp.AAR
来自 myapp.AAR:
myapp.AAR/applicationContext.xml
您不能修改包含在任何 ?AR 文件(WAR、JAR、EAR、AAR、...)中的文件。它基本上是一个 zip 存档,修改它的唯一方法是解压缩它,进行更改,然后再次压缩它。
如果您试图让正在运行的应用程序自行修改,请认识到 1) 许多容器出于各种原因从 ?AR 文件的分解副本运行,并且 2) 您不太可能这样做无论如何都可以即时修改文件,除非您计划在更改后重新启动应用程序或编写大量代码来监视更改并在之后以某种方式刷新您的应用程序。无论哪种方式,您最好弄清楚如何以编程方式进行所需的更改,而不是尝试重写正在运行的应用程序。
另一方面,如果您不是在谈论让应用程序修改自身,而是更改 WAR 文件然后部署新版本,那么这正是我上面所说的。使用jar工具展开,修改展开后的目录,然后用jar再次压缩。然后像新的 war 文件一样部署它。
You can edit a war as follow,
//You can loop through your war file using the following code
ZipFile warFile = new ZipFile( warFile );
for( Enumeration e = warFile.entries(); e.hasMoreElements(); )
{
ZipEntry entry = (ZipEntry) e.nextElement();
if( entry.getName().contains( yourXMLFile ) )
{
//read your xml file
File fXmlFile = new File( entry );
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
/**Now write your xml file to another file and save it say, createXMLFile **/
//Appending the newly created xml file and
//deleting the old one.
Map<String, String> zip_properties = new HashMap<>();
zip_properties.put("create","false");
zip_properties.put("encoding","UTF-8");
URI uri = URI.create("jar:" + warFile.toUri() );
try( FileSystem zipfs = FileSystems.newFileSystem(uri, zip_properties) ) {
Path yourXMLFile = zipfs.getPath( yourXMLFile );
Path tempyourXMLFile = yourXMLFile;
Files.delete( propertyFilePathInWar );
//Path where the file to be added resides
Path addNewFile = Paths.get( createXMLFile );
//Append file to war File
Files.copy(addNewFile, tempyourXMLFile);
zipfs.close();
}
}
}