-1

So currently I can read and write to an xml file when I'm running the program in eclipse, but when I export it as a .jar the writing does not work any more.

public void addHighscores(String naam, String score){
            Document document = null;
        Element root = null;

        InputStream fis = getClass().getResourceAsStream("Highscores.xml");
        SAXBuilder sb = new SAXBuilder();
        document = sb.build(fis);
        root = document.getRootElement();
        fis.close();


        Element player = new Element("player");
        player.addContent(new Element("name").setText(naam));
        player.addContent(new Element("score").setText(score));
        root.addContent(player);
        document.setContent(root);

        FileWriter writer = new FileWriter(path);
        XMLOutputter outputter = new XMLOutputter();
        outputter.setFormat(Format.getPrettyFormat());
        outputter.output(document, writer);
        outputter.output(document, System.out);
        writer.close();}

That's the code for the writer. The xml file is saved in the same folder as the code, I don't understand why it can read but not write. Thanks in advance

2 Answers2

0

You can't write back to the jars on the classpath. What you can do, however, is add a directory to the classpath and read/write the XML file from that location. That'll work just fine for you. If this is a web app running in Tomcat, the Tomcat lib directory is part of the classpath by default. So one thing you can is read from say "/myapp/conf/stuff.xml" and put myapp/conf/stuff.xml under lib.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
  • Beware, it is common that the lib directory is not writable by web application for security reasons. – Serge Ballesta Jun 10 '14 at 12:55
  • Not making a webapp, but how would I go about adding a directory and reading/writing? Because again, when starting the program in eclipse and simply saying FileInputStream fis = new FileInputStream("input/Highscores.xml"); works in eclipse, but not when in a jar – user3535989 Jun 10 '14 at 13:03
0

After building a jar you can not edit it on the classpath. But you can definetly add a path in your classpath. You can place the files on that path and read from there. Please check this .

Community
  • 1
  • 1