我有保存和加载瓷砖地图的代码:
public void load(File loadFile) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(loadFile);
Element root = document.getRootElement();
for (Object tiles : root.getChildren()) {
Element e = (Element) tiles;
int x = Integer.parseInt(e.getAttributeValue("X"));
int y = Integer.parseInt(e.getAttributeValue("Y"));
worldTiles[x][y] = new Tile(tile.id, new Vector2f(x
* Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT));
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void save(File saveFile) {
Document document = new Document();
Element root = new Element("blocks");
document.setRootElement(root);
for (int x = 0; x < TILE_WIDTH - 1; x++) {
for (int y = 0; y < TILE_HEIGHT - 1; y++) {
Element tiles = new Element("block");
tiles.setAttribute("x",
String.valueOf((int) (worldTiles[x][y].getX())));
tiles.setAttribute("y",
String.valueOf((int) (worldTiles[x][y].getY())));
tiles.setAttribute("type",
String.valueOf(worldTiles[x][y].getType()));
root.addContent(tiles);
}
}
XMLOutputter output = new XMLOutputter();
try {
output.output(document, new FileOutputStream(saveFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
然后我在我的输入处理程序中调用代码,如下所示:
if(Keyboard.isKeyDown(Keyboard.KEY_F)){
world.save(new File("save.xml"));
}
if(Keyboard.isKeyDown(Keyboard.KEY_G)){
world.load(new File("save.xml"));
}
但是,我得到一个空指针异常。老实说,这没有任何意义,因为我在尝试加载之前创建了保存文件,所以这不是问题。我的 worldTile[][] 数组中有瓷砖,所以它不会在那里抛出错误。一些额外的信息,Tile 构造函数如下所示:
public Tile(int id, Vector2f position)
有什么帮助吗?