java.util.Properties不起作用

时间:2016-09-14 13:35:39

标签: java xml properties

我正在开发游戏,并且我使用java.util.Properties来保存日期。 我想将这些日期保存在XML文件中,但我遇到了一些问题...

这是创建OutputStream,XML文件和目录(如果不存在)的方法。

public String save(String date, String vname){
    //This is the method which saves the dates

   //There are some controls
    if(!dir.exists()){
        game.log.debug("Saves directory not exists. Creating...", -3);
        if(!dir.mkdirs())
            game.log.debug("Impossible to create directory. The game can't save dates.", -1);
        else game.log.debug("\"C:/MakeGame/saves\" successfully created.", 1);
    }

    if(ostream == null && save == null){
        try {
            if(save == null){
                save = new File(dir.getPath() + game.getName() + " save.xml"); //THIS CREATES THE SAVE FILE IN XML FORMAT
                ostream = new FileOutputStream(save); //THIS CREATE A NEW FILEOUTPUTSTREAM
            }
            if(!save.exists()){
                if(!save.createNewFile()) //NEW XML FILE CREATION
                    game.log.debug("Impossible to make new save file. The game can't save dates.", -1);
                else game.log.debug("\"C:/MakeGame/saves/" + save.getName() + " \" successfully created.", 1);
            }
        } catch (FileNotFoundException ex) {
            game.log.debug("File not found. The game can't save dates.", -1);
        } catch (IOException ex) {
            Logger.getLogger(Saver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    String saved = "";

    if(save.exists()){
        saved = (String) saves.setProperty(date, vname); //SET THE PROPERTY

        try {
            saves.storeToXML(ostream, "Don't change this save files. This files are used by the games to load the progresses."); //STORES THE DATES IN XML FORMAT.
        } catch (IOException ex) {
            game.log.debug("Impossible to store this saves. The game can't save dates", -1);
        }
    }

    return saved;
}

当我加载日期时,我使用另一种方法。

public String load(String vname) throws FileNotFoundException{
        if(save == null){
            save = new File(dir.getPath() + game + " save.save");
            istream = new FileInputStream(save);
        }

        if(save.exists()) try {
            saves.load(istream);
        } catch (IOException ex) {
            game.log.debug("Error loading dates from save file. The game can't load dates.", -1);
        }
        if(!saves.isEmpty()){
            game.log.debug(saves.getProperty(vname) + " successfully loaded.", 0);
            return saves.getProperty(vname);
        }
        return null;
    }

但它总是返回null。为什么呢?

1 个答案:

答案 0 :(得分:0)

您在date方法中使用save()字符串作为属性键,然后尝试在vname方法中使用load()作为键。

使用vname作为密钥,date作为设置属性的值,如下所示:

saved = (String) saves.setProperty(vname, date); //SET THE PROPERTY