Updating an XML file inside the Jar executable

Hello all!
I would like to ask how can i update an XML file that is packaged inside my jar file?
For intstance:
I have a Java Application in NetBeans
Inside a package i have constructed a custom .xml file.
I can read from this file using
.....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
I want to update an entry in my xml file so the jar contains now the newly updated file.
Thanks everyone who spends his time to read this. Hope someone can help me.

Even if it were possible, it would be a bad idea. A jar file is something you deploy. It can be really hard to manage ongoing maintenance if the thing you deploy changes after you've deployed it.
Just create a file, in an appropriate place given the user's OS, to hold data that changes after the jar has been deployed. Your application will still be in a single jar; it's just that the application will happen to create additional content outside the jar.

Similar Messages

  • Updating an XML file inside the executable JAR.

    Hello all!
    I would like to askk how can i update an XML file that is packaged inside my jar file?
    For intstance:
    I have a Java Application in NetBeans
    Inside a package i have constructed a custom .xml file.
    I can read from this file using
    .....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
    I want to update an entry in my xml file so the jar contains now the newly updated file.
    Thanks everyone who spends hit time to read this. Hope someone can help me.

    Please don't cross-post:
    http://forums.sun.com/thread.jspa?threadID=5342194

  • How to read some files inside the jar

    Hi,
    I have an applet that runs with JWS. The user can input some information and then I need to show this information in a web page. As the application can be run offline, I cannnot use JSP�s to generate the web page. The information is saved in a xml file, so I use a xsl parser to generate the html code. The problem is that I have to include some javascript files (.js). I put these files inside the jar, but, how can I read these files, or how can I reference these files from inside the html page ?
    Thanks !

    You can use getClass().getResource(classpath)
    to get a stream version of the data from your
    jar file. If you need to put it in a file, you
    can write that stream to a file in a temp directory.
    classpath is the classpath of your js file

  • Java Files inside the jar file cannot be read or accessed through Eclpse

    The Java File inside the jar file of the eclipse cannot be accessed through the Eclipse . It shows error for the modules in the jar file .
    But when compiled with adding the jar files to the class path the compilation is successful .
    How can i browse through the files in the jar like going into the function definition .
    TIA ,
    Imran

    Open MPlayer OSX and show the playlist (command-shift-p) then drag the file into the playlist. Click the file in the playlist and click the "i"nfo button. What does it list for file, video and audio format?
    Not all of the codecs used in avi and wmv files are available for OS X so I'm guessing your file happens to be using one that isn't...

  • How to read, write file inside the JAR file?

    Hi all,
    I want to read the file inside the jar file, use following method:
    File file = new File("filename");
    It works if not in JAR file, but it doesn't work if it's in a JAR file.
    I found someone had the same problem, but no reply.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=180618
    Can you help me ? I have tried this for all night !
    Thanks in advance
    Leo

    If you want to read a file from the JAR file that the
    application is packaged in (rather than a separate
    external JAR file) you do it like this ...
    InputStream is =
    ClassLoader.getSystemResourceAsStream("filename");Better to use
    this.getClass().getClassLoader().getResourceAsStream();
    From a class near to where the data is. This deals with multiple classloaders properly.

  • How to read a file inside the JAR file

    Hi All,
    I want to save some preferences in a file called "preferences". I kept the preferences file under my java package.
    If i am running the code inside the NetBeans 6.9 IDE it's working file. But once i have created a JAR and try to run the application, it couldn't find the path.
    Please help me that how to resolve this issue. I don't want to save this preferences file outside of my JAR (i.e) within my java package.
    Here is the code,
    package mypackage;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    public class ReadFile
        private void writeFile()
            try
                OutputStream out = new FileOutputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                PrintWriter writer = new PrintWriter(out);
                writer.println("Hello Java!");
                writer.close();
                out.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        private void readFile()
            try
                FileInputStream fi = new FileInputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                BufferedReader br = new BufferedReader(new InputStreamReader(fi));
                System.out.println(br.readLine().trim());
                br.close();
                fi.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        public static void main(String[] args)
            ReadFile read = new ReadFile();
            read.writeFile();
            read.readFile();
    }If i run the JAR, i get the following error message,
    {color:#ff0000}*file:\my jar path\jarname.jar!\mypackage\preferences (The filename, directoryname, or volume label syntax is incorrect)*{color}

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • Editing xml file inside a Jar

    Hello ,
    After creating my desktop application i created a Jar for it, but when i tried to change my program settings through the jar(Which is set in an xml file), i found that the changes did not happen.
    After some search i found that i can only edit files in a Jar by re-creating the jar again.
    Sure there's another easier way ? .... This is a normal demand.
    If not then what's the best way to deliver my program to my clients ?
    Thanks ,
    Hesham

    pbrockway2 wrote:
    i found that i can only edit files in a Jar by re-creating the jar again.That's correct.
    You could consider using the [Preferences API|http://java.sun.com/javase/6/docs/technotes/guides/preferences/index.html] to store program settings.
    ... or put the altered config in an external XML file. You could still keep a default config XML in the jar.

  • How to read files outside the jar ?

    Hi all,
    One of my classes inside jar needs to read XML file that resides in the same location where the jar sits. I use MyClass.getClass().getResource("MyXMLFile.xml") but it keeps returning null.
    If I place the XML file inside the JAR, I can find it using above methods, but since I want the user to easily edit the XML file without opening the jar file and detach the XML file, I choose not to include the XML file inside the jar.
    Any help would be greatly appreciated.
    Setya

    Thanks for the dukes.
    My JDBC post on this forum discusses the issues of
    using Class-Path in your jar file. It works, but it
    may vary from system to system.
    Thanks also from my side: I have read recently your discussion about reading files in the jar's directory, since I had the same problem. So I was really glad to see your solution. However, I had one more problem, namely that I'm running my application sometimes from the jar, sometimes from the classes directly (debugging). In order to have always the correct path (although a different one) I have added some more lines to deal with that case. I hope that will be useful for you as well!
    Dieter Profos
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.net.URL;
    * @author pkwooster
    * @author Dieter Profos
    * @version 1.01 04/03/26
    public class ReadOutside extends Frame {
    private TextArea textArea;
    public static void main(String[] args) {
    // Create application frame.
    ReadOutside tc = new ReadOutside();
    tc.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    // Show frame
    tc.setSize(600,250);
    tc.setVisible(true);
    public ReadOutside() {
    textArea = new TextArea(20,80);
    add(textArea);
    readOutside(this);
    public void readOutside(Object o) {
    System.out.println(getCodeBasePath(o));
    /** Gets the absolute path of the directory where the JAR or CLASS file is
    * located. If the application is run from a jar file, the directory of the
    * jar file is returned; if it is run from a class file, the method will
    * return the directory path of the class file.
    * @param o The main class of the application.
    * @return The absolute directory path, or null if neither the class nor a
    * jar file could be found.
    public String getCodeBasePath(Object o) {
    Class c = o.getClass();
    URL url;
    // get the class name
    String className = c.getName();
    textArea.append("class name = " + className + "\n");
    // replace package periods by file separators
    className = className.replace('.','/');
    ClassLoader cl = c.getClassLoader();
    if (cl == null)
    cl = ClassLoader.getSystemClassLoader();
    url = cl.getResource(className + ".class");
    String xPath = url.toExternalForm();
    textArea.append("url = " + url + "\n");
    textArea.append("extPath = " + xPath + "\n");
    // make sure that the path starts with jar:file:
    if (xPath.startsWith("jar:file:")) {
    // remove jar:file: + the subsequent file separator
    xPath = xPath.substring("jar:file:".length()+1);
    int n = xPath.indexOf("!");
    if (n < 0)
    n = xPath.length();
    String jarPath = xPath.substring(0, n);
    textArea.append("jar file path = " + jarPath + "\n");
    n = jarPath.lastIndexOf("/");
    String jarDir = jarPath.substring(0, n+1);
    textArea.append("jar dir = " + jarDir + "\n");
    return jarDir;
    else { // if program is run from its class file (development phase!)
    if (xPath.startsWith("file:")) {
    // remove file: + the subsequent file separator
    xPath = xPath.substring("file:".length()+1);
    textArea.append("class file path = " + xPath + "\n");
    int n = xPath.lastIndexOf("/");
    String classDir = xPath.substring(0, n+1);
    textArea.append("class dir = " + classDir + "\n");
    return classDir;
    return null;

  • Extracting and updating files inside a JAR file... from my code

    Hi.
    I need some help in the following:
    from my code, I need to search a JAR file, open it, unzipped it, then I need to search a xml and property files inside the JAR, after that I need to modify the files and finally, my code has to save the changes and update the JAR file. All that must be from my java code.
    How can I do that? I am trying to use Runtime.getRunTime().exec().... but I am not sure that it works. Besides, I don�t know what command to include in the exec() method. Is there any way to do that?
    Thanks

    The normal reason I see for this requirement is that people want to update a properties or data file. The approach I use it that I first look for the data file in a well defined location and if I find it I use it and update it as required. If I don't fine it I create it base on a template file read from the jar file using getResourceAsSrream().
    In this way I never have to update the jar file.

  • Validating xml-files inside jar-files  for JWS

    I want to use xml-files inside a jar-file and want to validate them with dtd-files,
    located in the same jar-file. This does work, but only as long as the dtd-file is
    in the same directory as the xml-file.
    For example, I have no problem, with a DOC Type-statement like
    <!DOCTYPE questestinterop SYSTEM "ims_qtiv1p1.dtd" >
    With this statement, however, one needs an approprate dtd in every directory containing an XML-file of that type.
    If however i want to gather the necessary dtd's in a directory one (or more) levels above with a DOCTYPE-statement of the form
    <!DOCTYPE questestinterop SYSTEM "../ims_qtiv1p1.dtd" >
    I get error messages of the form
    java.io.FileNotFoundException: JAR entry Mikro/Marshall/BookQuestions/../ims_qtiv1p1.dtd not found in C:\Dokumente und Einstellungen\wreiss\Anwendungsdaten\Sun\Java\Deployment\javaws\cache\http\Dwiwi.upb.de\P80\DM~vwl08\DMOViSS\DMoviss_current\RMMikro.jar
         at org.apache.crimson.parser.Parser2.fatal(Unknown Source)
         at org.apache.crimson.parser.Parser2.externalParameterEntity(Unknown Source)
         at org.apache.crimson.parser.Parser2.maybeDoctypeDecl(Unknown Source)
         at org.apache.crimson.parser.Parser2.parseInternal(Unknown Source)
         at org.apache.crimson.parser.Parser2.parse(Unknown Source)
         at org.apache.crimson.parser.XMLReaderImpl.parse(Unknown Source)
         at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(Unknown Source)
         at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
         at oviss.competenceCenter.XMLExpert.setElements(XMLExpert.java:245)
    though the dtd-file is in the parent-directory (inside the jar) and the unpacked xml-file can be successfully validated.
    Why does this happen. How can one use a single dtd for multiple xml-files (of the same type) in different directories?.
    Thanks
    Winfried Reiss

    In reply to myself, replacing the HTMLBrowser constructor with this;
    public HTMLBrowser()
                  URL url;
                  try
                       // Construct the URL
                       url= this.getClass().getResource('/'+dir+'/'+startPage);
                       setPage(url);
                  catch (Exception e)
                  System.out.println( "Problem setting help homepage");
                 setEditable(false);
                 addHyperlinkListener(new LinkListener(this));
            }made it work. This is because seemingly you need '/' at the start of the resouce's path and '/' as the separator, regardless of platform.
    I hope this helps someone else.
    John

  • Changing values in property file inside a jar in an ear

    Hi,
    I have an application that contains EJB. The environment values needed for initial context of the ejb is kept in a .properties file. I have created an ear of the application. Inside the ear there is a jar which contains the .properties file. I need to deploy the ear to different environments. However before deploying I need some kind of script to change the values in the .properties file inside the jar in the ear.
    Can anyone provide some help/pointers about how can I achieve it (Using ANT/WLST)

    WLST does not have any capability to update a JAR.
    WLS 10.3 (still in tech preview) has the ability to override properties
    files inside the jar with an external properties file. This would allow you
    to deploy the same ear to different environments, and then only deploy a
    different properties file in the plan directory.
    <Rishi Shah> wrote in message news:[email protected]..
    Hi,
    I have an application that contains EJB. The environment values needed for
    initial context of the ejb is kept in a .properties file. I have created an
    ear of the application. Inside the ear there is a jar which contains the
    .properties file. I need to deploy the ear to different environments.
    However before deploying I need some kind of script to change the values in
    the .properties file inside the jar in the ear.
    Can anyone provide some help/pointers about how can I achieve it (Using
    ANT/WLST)

  • Reading a file in the JAR

    i have a jar with class files and xml files in it. my application uses this jar and a particular class has a link to the xml. but while compiling, it shows path not found. the application couldnt read the xml file in the jar. how to set the path or read the xml file
    XML file in JAR:
    SQLMaps/admin/sample.xml [folder structure inside the jar file]
    my application has a path like SQLMaps/admin/sample.xml
    but how do we point to the xml file in the jar
    Regards
    Pradheep

    thanks anyway
    but i need the application to read the xml file in the jar file
    to be more clear.
    the jar file has xml in a specified folder.

  • How to update XML file from the program

    i am new in abap , and i have the following issue,so plz anyone who knows how to do it
    Background :
    An XML file is used as the datasource for a Flex Application. From time to time this requires updating with new staff details.
    i have already saved the xml file in the c drive with the name C:\AdvAC\AC1\bin-debug\assets\staff
    Requirement :  Write a Dialog transaction with the following text input fields.
    Reference Indicator.     (Char10)
    Staff No          (NUMC, Length 5)
    Name               (Char50)
    Room               (Numc, length 3)
    Phone               (Numc Length 7)
    Mail               (char30)
    in screen 100
    The transaction should also have an u201CUpdate Fileu201D button, which when pressed :
    1) Loads the file C:\AdvAC\AC1\bin-debug\assets \ into an ITAB.
    2) Inserts the data into the ITAB using the following XML format.
    <staff>
    <ref_ind> Reference Indicator.</ref_ind>
    <staff_no> Staff No </staff_no>
    <name> Name </name>
    <room> Room </room>
    <phone> Phone </phone>
    <mail> Mail </mail>
    </staff>
    all should be inside  <allstaff> </allstaff> tagsu2026.
    Writes the ITAB back to the file.
    thanx all

    this is what i have done but i dont know how to do the rest. i will apprecite any help from u.
    Edited by: man700s on Feb 16, 2010 6:58 AM
    REPORT  Z_XML_FILE_UPDATE.
    TYPES: BEGIN OF ts_staff,
             REF_IND(10)  TYPE c,
             Staff_No(5)  TYPE c,
             Name(50)     TYPE c,
             Room(3)      Type n,
             Phone(7)     Type n,
             Mail(30)     Type c,
           END OF ts_staff.
    DATA: t_staff TYPE TABLE OF ts_staff WITH HEADER LINE.
    DATA: w_staff Type ts_staff.
    DATA T_STRING TYPE TABLE OF STRING.
    DATA W_STRING TYPE STRING.
    call SCREEN 100.
    PERFORM upload_xml_file.
    PERFORM update_xml_tab.
    *PERFORM download_xml_file.
    MODULE USER_COMMAND_0100 INPUT.
    W_STRING = '<allstaff>'.
      APPEND w_string to t_string.
      loop at t_staff into w_staff.
      w_string ='<staff>'.
      APPEND w_string to t_string.
      if T_staff-Ref_Ind = 'X'.
      CONCATENATE '<Ref_Ind>' w_staff-Ref_Ind '</Ref_Ind>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
      if T_staff-staff_no = 'X'.
      CONCATENATE '<staff_no>' w_staff-staff_no '</staff_no>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
      if T_staff-name = 'X'.
      CONCATENATE '<name>' w_staff-name '</name>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
    if T_staff-room = 'X'.
      CONCATENATE '<room>' w_staff-room '</room>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
      if T_staff-phone = 'X'.
      CONCATENATE '<phone>' w_staff-phone '</phone>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
      if T_staff-mail = 'X'.
      CONCATENATE '<mail>' w_staff-mail '</mail>' into w_string.
      APPEND w_string to t_string.
      ENDIF.
      w_string = '</staff>'.
      append w_string to t_string.
    ENDLOOP.
      W_STRING = '</allstaff>'.
      APPEND w_string to t_string.
    ENDMODULE.               
    Edited by: man700s on Feb 16, 2010 7:01 AM

  • How can I fill structure from the line with contetnt of a XML file inside?

    How can I fill structure from the line with contetnt of a XML file inside?
    I have array of lines with XML documents inside. All XML's have the same structure.
    I need to fill array of structures (with the same structure like given XML's) from data of these XML's.
    How can I do this? I am trying Transformation with ora:parseEscapedXML, but receive error: "XPath expression failed to execute.
    Error while processing xpath expression, the expression is "ora:processXSLT("Transformation_1.xsl", bpws:getVariableData("ProcessedFiles"))", the reason is javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: Could not find function: parseEscapedXML.
    Please verify the xpath query."

    Ive posted the new code but now I'm getting a FileAlreadyExistException error. How do I handle this exception error correctly in my code?
    import java.io.IOException;
    import java.nio.file.FileAlreadyExistsException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println(templateElement.getAttribute("name")+ ".xml");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      String fileName = templateElement.getAttribute("name") + ".xml";
      Files.createFile(Paths.get(fileName));
      System.out.println("File" + ":" + fileName + ".xml created");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

  • How to get a file in the same dir with the jar-executable

    Hi,
    I need to read/write a file that exists in the same directory with the jar-executable. How can i do that? I think that when i specify no path for the file, the file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and the file are.
    Thanx in advance

    Hi,
    I need to read/write a file that exists in the same
    directory with the jar-executable. How can i do that?
    I think that when i specify no path for the file, the
    file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and
    the file are.
    Thanx in advance
    When you specify no path for the file, the file has to be in the directory where the virtual machine was started. ( the directory the java command was invoked in .)
    If you can't control the directory in which the vm is started, but you know the name of the .jar file you can do the following. This trick takes advantage of the fact that if you are using classes in a jar file, the name of the jar file must be in your classpath.
    public static String getPathOfJar( String nameOfJar )
    throws Exception
    StringTokenizer st = new StringTokenizer(
    System.getProperty( "java.class.path" ) ,
              System.getProperty( "path.separator" ) );
    String jarfile = "";
    while ( st.hasMoreTokens() )     
    String token = st.nextToken();
    if ( token.indexOf( nameOfJar ) > -1 )
    jarfile = token;
    break;
    if ( jarfile.equals("") ) throw new Exception( "Jar not found in classpath" );
    String path = jarfile.substring( 0 , jarfile.indexOf( nameOfJar ) );
    return path;
    //To open a file in the same directory as the sun archive tools.jar
    File f = new File( getPathofJar( "tools.jar" ) + "someFile.txt" );

Maybe you are looking for

  • How to secure firewire drive data for multi user mac ?

    I have a couple of external firewire hard drives attached to my mac which contain all my work files. My 6 yr son has started using my mac so I have set him up his own account and set up the parental controls etc. BUT - is there any way I can set thin

  • Check on Goods Issue

    Hi, My client is asking a solution for scenario whereby- eg: activity1 material1 qty 10 material2 qty 20 Now client wants that no goods issue can happen on apart from the materials atttached to activity. Do we have some solution in standard or should

  • How can I get the cursor to appear in the main search window on the Google home page by default?

    The cursor in my Firefox appears in the address bar. I would like it to appear by default in the main search window on my default home page, Google.com. How?

  • Premiere pro / After Effects CS6 upgrade , render doesn't save ?

    Hi, I have just upgraded CS5.5 to CS6. I have opened and converted a previous project in CS6 which is linked to After Effects via the dynamic link. The media opened ok but even though it was fully rendered and saved from the previous version I had to

  • While configuring Shared Services

    While installing Essbase System 9, i am not able to configure Shared Services. The default password, which i tried was 'password', but it was not taking? pls help.