有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

WAR存档中的xml Java编辑文件

我一直在论坛上阅读关于如何读取/编辑归档文件中的文件,但仍然无法得到答案。主要使用getResourceAsStream,并且必须在其类路径内

我需要做的是,以给定的文件路径作为输入读取并更新xml文件,然后将其重新部署到Tomcat。 但到目前为止,我仍然无法回答如何在给定完整路径作为输入的WAR归档文件中编辑AAR文件中的xml文件。谁能帮帮我吗

例如,我想编辑applicationContext。xml文件:

C:/webapp。战争

从网络应用程序。WAR文件:

网络应用。WAR/WEB-INF/services/myapp。AAR

来自myapp。AAR:

我的应用。AAR/applicationContext。xml


共 (2) 个答案

  1. # 1 楼答案

    你不能修改任何文件中包含的文件吗?AR文件(WAR、JAR、EAR、AAR等)。它基本上是一个zip存档,修改它的唯一方法是解压它,进行更改,然后再次压缩

    如果你试图让一个正在运行的应用程序修改自己,那么你是否认识到1)许多容器都是从一个已分解的应用程序副本运行的?由于各种原因,AR文件,以及2)不管怎样,动态修改文件都不太可能对您有任何好处,除非您计划在更改后重新启动应用程序,或者编写大量代码来监视更改,并在更改后以某种方式刷新应用程序。不管是哪种方式,与试图重写正在运行的应用程序相比,您最好弄清楚如何以编程方式进行所需的更改

    另一方面,如果你说的不是让一个应用程序修改自己,而是更改一个WAR文件,然后部署新版本,那就是我上面说的。使用jar工具分解它,修改分解的目录,然后使用jar再次压缩它。然后像部署新的war文件一样部署它

  2. # 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();  
    
            }
        }
    }