Home > front end >  Delete existing file and create/write data into same file using TransformerFactory within a loop
Delete existing file and create/write data into same file using TransformerFactory within a loop

Time:02-22

I want to transform the input.XML file with XSL and overwrite the output.XML file in a loop so that I get the final output.XML file.

I am able to do this, however instead of overwriting the output.XML file, it's appending the same file with all iteration data of loop.

To resolve this issue, I tried to delete the existing output.XML file in loop only just before transforming the input.XML file with XSL, but getting error -

java.nio.file.FileSystemException: Output.xml: The process cannot access the file because it is being used by another process.

So, I'm NOT able to delete the existing file also not able to overwrite the output.xml file.

Can anyone help on this pls. I believe resolving any one of these issue should help out.

Thanks

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
    // TODO Auto-generated method stub      
    
    try {
        
        Double currentValue = 1.0;
        
        String inputXMLPath = "C:/MySystem/Input.xml";
        
        String outputXMLPath = "C:/MySystem/Output.xml";
        
        StreamSource inputStream = new StreamSource(inputXMLPath);
        
        FileOutputStream opStream = new FileOutputStream(new File(outputXMLPath));
        
        while (currentValue != 7.0) {
            String xslPath = "C:/MySystem/input.xsl";
            Path path = FileSystems.getDefault().getPath(outputXMLPath);
            Files.delete(path);
            
            performTransformation(xslPath, inputStream, opStream, outputXMLPath);
            StreamSource secondStream = new StreamSource(outputXMLPath);
            inputStream = secondStream;
            currentValue  ;
            opStream.flush();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void performTransformation(String xslPath, StreamSource inputStream, FileOutputStream opStream,
        String outputXMLPath) throws Exception {        
    
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    transformer = tFactory.newTransformer(new StreamSource(xslPath));
    transformer.transform(inputStream, new StreamResult(opStream));
    opStream.flush();
}

Input.xml

    <?xml version="1.0"?>
    <ASR_SERVICE_REQUEST xmlns="http://www.atis.org/OBF/ASR/UOM-ASR">
<HDR>
    <MESSAGE_ID>TEST123</MESSAGE_ID>
    <CCNA>TEST</CCNA>
    <MSG_TIMESTAMP>2021-10-04T12:25:53-06:00</MSG_TIMESTAMP>
    <ICSC>MS02</ICSC>
    <ASOG_VER>61</ASOG_VER>
</HDR>
<SWITCHED_ETHERNET_EVC_SVC>
    <ASR>
        <ADMIN>
            <CCNA>LTL</CCNA>
            <PON>GETPOM-021421</PON>
            <VER>01</VER>
            <ICSC>MS02</ICSC>
            <D_SENT>20211004</D_SENT>
            <T_SENT>12:25:53</T_SENT>
            <DDD>20211206</DDD>
            <PROJECT>EVPLWESTYUMAFTTT</PROJECT>
            <REQTYP>ED</REQTYP>
            <ACT>N</ACT>
            <QSA>01</QSA>
            <EVCI>B</EVCI>
            <SEI>Y</SEI>
            <RTR>S</RTR>
            <CKR>CDC101/EVC10/PXRAZB0001A/PXRAZ00028A/LMN</CKR>
            <UNIT>C</UNIT>
            <PIU>100</PIU>
            <QTY>1</QTY>
            <BAN>E</BAN>
            <SPEC>SVCMUX</SPEC>
            <ASR_REMARKS>TEST DATA </ASR_REMARKS>
        </ADMIN>
        <BILLING>
            <BILLNM>TEST LLC</BILLNM>
            <ACNA>DWX</ACNA>
            <TE>G</TE>
            <FUSF>E</FUSF>
            <BILL_STR>9601 S. Meridian Blvd.</BILL_STR>
            <BILL_CITY>ENGLEWOOD</BILL_CITY>
            <BILL_STATE>CO</BILL_STATE>
            <BILL_ZIP>80112</BILL_ZIP>
            <BILLCON>Billing Dep</BILLCON>
            <BILLCON_TEL>7205146400</BILLCON_TEL>
            <VTA>96</VTA>
            <VTAI>A</VTAI>
            <PNUM>R287357</PNUM>
        </BILLING>
        <CONTACT>
            <INIT>Test</INIT>
            <INITIATOR_TEL>9090909090</INITIATOR_TEL>
            <DSGCON>Test</DSGCON>
            <DSGCON_TEL>9090909090</DSGCON_TEL>
            <DSG_FAX_NO>9090909090</DSG_FAX_NO>
            <DSG_EMAIL>[email protected]</DSG_EMAIL>
            <DRC>AN3</DRC>
            <SITECON>David</SITECON>
            <SITECON_TEL>6022829511</SITECON_TEL>
            <SITECON_EMAIL>[email protected]</SITECON_EMAIL>
            <IMPCON>David</IMPCON>
            <IMPCON_TEL>6022829511</IMPCON_TEL>
        </CONTACT>
    </ASR>
    <SES>
        <SES_SVC_DETAILS>
            <NC>KRE0</NC>
            <NCI>02LNF.A02</NCI>
            <SECNCI>02CXF.1GE</SECNCI>
            <ES>S</ES>
            <PROFE>P1</PROFE>
            <PROFI>P1</PROFI>
        </SES_SVC_DETAILS>
        <SES_LOCATION>
            <SALI>
                <PI>Y</PI>
                <EUNAME>TEST LLC</EUNAME>
                <ADDR>
                    <SANO>2863</SANO>
                    <SASD>S</SASD>
                    <SASN>Pacific</SASN>
                    <SATH>Avenue</SATH>
                    <CITY>YUMA</CITY>
                    <STATE>AZ</STATE>
                    <ZIP>85365</ZIP>
                </ADDR>
                <NCON>Y</NCON>
                <JS>D</JS>
                <LCON>David Rhodes</LCON>
                <ACTEL>6022829511</ACTEL>
                <LCON_EMAIL>[email protected]</LCON_EMAIL>
            </SALI>
        </SES_LOCATION>
    </SES>
    <EVC>
        <EVC_DETAILS>
            <EVCNUM>0001</EVCNUM>
            <NC>VLP-</NC>
            <NUT>02</NUT>
            <EVCCKR>CDC101/EVC10/PXRAZB0001A/PXRAZ00028A/LMN</EVCCKR>
            <UNI_MAPPING>
                <UREF>01</UREF>
                <AUNT>A</AUNT>
                <UACT>N</UACT>
                <NCI>02VLN.V</NCI>
                <CEVLAN_MAPPING>
                    <VACT>N</VACT>
                    <CE_VLAN>
                        <CE_VLAN_START>3008</CE_VLAN_START>
                    </CE_VLAN>
                </CEVLAN_MAPPING>
                <LREF_MAPPING>
                    <LREF>1</LREF>
                    <LOSACT>N</LOSACT>
                    <LOS>P1</LOS>
                    <BDW>UNI</BDW>
                </LREF_MAPPING>
            </UNI_MAPPING>
            <UNI_MAPPING>
                <UREF>02</UREF>
                <EI>Y</EI>
                <UACT>N</UACT>
                <NCI>02VLN.V</NCI>
                <RUID>19.KXGS.581526..MS</RUID>
                <CEVLAN_MAPPING>
                    <VACT>N</VACT>
                    <CE_VLAN>
                        <CE_VLAN_START>3008</CE_VLAN_START>
                    </CE_VLAN>
                </CEVLAN_MAPPING>
                <LREF_MAPPING>
                    <LREF>1</LREF>
                    <LOSACT>N</LOSACT>
                    <LOS>P1</LOS>
                    <BDW>UNI</BDW>
                </LREF_MAPPING>
            </UNI_MAPPING>
        </EVC_DETAILS>
    </EVC>
</SWITCHED_ETHERNET_EVC_SVC>
</ASR_SERVICE_REQUEST>

Input XSL

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asog="http://www.atis.org/OBF/ASR/UOM-ASR" xmlns:notify="http://www.atis.org/OBF/ASR/UOM-ASRNotify" exclude-result-prefixes="asog notify">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="*">
        <xsl:copy>
            <xsl:if test="local-name()='HDR'">
                <xsl:element name="ASOG_VER" namespace="{namespace-uri()}">
                    <xsl:text>62</xsl:text>
                </xsl:element>
            </xsl:if>
            <xsl:for-each select="@*">
                <xsl:if test="local-name() != 'GOV' and local-name() != 'TLR'">     
                    <xsl:copy/>
                </xsl:if>  
            </xsl:for-each>
            <xsl:value-of select="text()"/>
            <xsl:apply-templates select="*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="asog:ASR_SERVICE_REQUEST/asog:HDR/asog:ASOG_VER">
    </xsl:template>

    <xsl:template match="asog:ASR_SERVICE_RESPONSE/asog:HDR/asog:ASOG_VER">
    </xsl:template>
    <xsl:template match="//notify:HDR/notify:ASOG_VER">
    </xsl:template>
</xsl:transform>

CodePudding user response:

Pretty sure you can't edit or delete this file because the input stream is still open, that's why it is still in use if you can close the input stream then delete the XML file and then make a new one it should work no problem.

This should fit your use case assuming the file is always called the same thing.

Also the deleteIfExists(Path) method is useful as it will still delete the file but will not throw an exception if it does not exist.

CodePudding user response:

You can't delete the file because you haven't closed it. But instead of deleting it, why don't you re-create the file inside the loop, instead of outside it:

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
    // TODO Auto-generated method stub      *** DELETE THIS LINE ***
    
    try {
        
        Double currentValue = 1.0;
        
        String inputXMLPath = "C:/MySystem/Input.xml";
        
        String outputXMLPath = "C:/MySystem/Output.xml";
        
        StreamSource inputStream = new StreamSource(inputXMLPath);
        
        // *** DANGER! COMPARING DOUBLES IS PRONE TO ERRORS! ***
        while (currentValue != 7.0) {
            // *** USE TRY-WITH-RESOURCES TO ENSURE THE STREAM GETS CLOSED ***
            try (FileOutputStream opStream = new FileOutputStream(outputXMLPath)) {
        
                String xslPath = "C:/MySystem/input.xsl";
            
                performTransformation(xslPath, inputStream, opStream, outputXMLPath);
                StreamSource secondStream = new StreamSource(outputXMLPath);
                inputStream = secondStream;
                currentValue  ;
            }
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
  • Related