【问题标题】:Java edit file inside WAR archiveWAR 档案中的 Java 编辑文件
【发布时间】:2013-06-05 01:47:38
【问题描述】:
我一直在论坛上阅读有关如何读取/编辑存档中的文件,但仍然无法得到我的答案。主要使用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
【问题讨论】:
标签:
java
xml
tomcat
file-io
war
【解决方案1】:
您不能修改任何 ?AR 文件(WAR、JAR、EAR、AAR、...)中包含的文件。它基本上是一个 zip 存档,修改它的唯一方法是解压缩,进行更改,然后重新压缩。
如果您尝试让正在运行的应用程序自行修改,请认识到 1) 许多容器出于各种原因从 ?AR 文件的分解副本运行,以及 2) 修改文件不太可能对您有任何好处无论如何,除非您计划在更改后重新启动应用程序或编写大量代码来监视更改并在之后以某种方式刷新您的应用程序,否则无论如何都在运行中。无论哪种方式,您最好弄清楚如何以编程方式进行所需的更改,而不是尝试重写正在运行的应用程序。
另一方面,如果您不是在谈论让应用程序修改自身,而是更改 WAR 文件然后部署新版本,那么这正是我上面所说的。使用jar工具解压,修改解压后的目录,然后用jar再次压缩。然后像新的战争文件一样部署它。
【解决方案2】:
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();
}
}
}