簡體   English   中英

WAR存檔中的Java編輯文件

[英]Java edit file inside WAR archive

我一直在論壇上閱讀有關如何讀取/編輯存檔中文件的信息,但仍然無法得到我的答案。 主要使用getResourceAsStream,並且必須在其classpath中。

我需要做的是,使用給定的文件路徑作為輸入讀取和更新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();  

        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM