1

I know it's been asked before and answered, but i just can't make it work.

So, my files hierarchy is:

+ Project
  + build.xml
  + save.xml
  + src
  + build

I have the "save" file to save the state of a game in a given instant. It should be easy to overwrite and easy to read to load everything again in the game.

My save() is like this, and it seems to be working:

 public void save(Game game) throws IOException{
    Document doc = DocumentHelper.createDocument();
    doc.add(game.save());
    File save=null;
    save = new File("./save.xml");

    FileWriter writer = new FileWriter(save);
    doc.write( writer);
    writer.close();
}

game.save() is a method in the game that actually does what i want to do. It does it recursively and all, and i know it works fine because i opened the XML file with another program.

So, my problems begins here. My getinfofromxml() method is:

public Game getinfofromxml() throws IOException{
    Game game;
    SAXReader reader = new SAXReader();
    try{
        URL fileWithData=getClass().getResource("./save.xml");
        Document document = reader.read(fileWithData);
        Element alreadySavedGame= document.getRootElement();
        game= getGameSaved(alreadySavedGame);
    }catch(DocumentException ex){
        throw new IOException();
    }
    return game;
} 

My problem is, when try to run it (via ant), no test will pass. I go to eclipse, and i can see that when i try to load the game, it throws Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

I've tried changing the line URL fileWithData=getClass().getResource("./save.xml"); to URL fileWithData=getClass().getResource("save.xml"); and URL fileWithData=getClass().getResource("../save.xml"); and things like that, but it says always the same.

Any idea?

Thank you for reading

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
FDrico
  • 37
  • 2
  • 7

1 Answers1

1

so, if you use getResource() it will try to find your file using the classloader that was used to load that class. this might be (later at least) the jar file your app is packaged in, and i don't think that's you're trying to load your savegame from there :)

i'd load the file the same way you save it:

URL fileWithData= new File( "save.xml" ).toURI().toURL(); 

(you might have to catch an extra exception)

kritzikratzi
  • 19,662
  • 1
  • 29
  • 40