简体   繁体   中英

how can i get a file path from URL object

TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        URL url = getClass().getResource("CustomerDedupeRules.xml");
        StreamResult result = new StreamResult(new File(url.getPath()));
        transformer.transform(source, result);
    } catch (Exception e) {
        logger.error(e);
    }

i am trying to update an xml file which exists in my classes folder. but i am getting file not found exception if i use url.getPath() or url.getFile(). the code is working fine if i hardcode the file path instead of using URL object. please suggest me what is wrong with my approach.

thanks

I don't think you can obtain a File from a classpath resource. Because a classpath resource is typically packaged up in a JAR file. And IMHO it doesn't make sense to update a JAR file that is currently in use.

Where is this file ? If it is inside a jar, you should use the openStream() method to get access to the contents. If it is not inside a jar, print the absolute path of the File using getAbsolutePath() and verify if it exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM