我正试图扫描我拥有的播放器数据文件,并将播放器数据设置为文件中的内容。该文件看起来像是我想保存数据到它,并读取播放器的数据。我要怎么做?
HP = 10
Atk = 2
Def = 5;我需要把这个和球员的健康联系起来。这是我所用的。
File dir = new File("c:\\Project0\\data\\Playerstuff");
if (!dir.exists()) {
if (dir.mkdirs()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
String fileName="hi";
File tagFile=new File(dir,fileName+".txt");
if(!tagFile.exists()){
try {
FileWriter fw = new FileWriter(tagFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("HP: " + p.getAtk());
bw.close();
Scanner s = new Scanner(tagFile);
s.findInLine("HP: ");
} catch (IOException ie) {ie.printStackTrace(); System.out.println("Error loading game directory");}
}发布于 2014-08-17 04:27:44
不知道你为什么要同时读和写,并且你保存数据的间隔似乎不适合被阅读。例如,我会尝试将数据保存为
HP=10
ATK=2
DEF=5然后当你阅读数据时:
Scanner s = new Scanner(tagFile);
while(s.hasNextLine()) {
String info = s.nextLine();
if (info.startsWith("HP") {
int hp = Integer.parseInt(info.substring(info.indexOf("=" + 1),info.length()));
p.setHP(hp);
}
else if (...) //Etc... for all the other values
}另一种方法是在不使用if/atk的情况下,始终将数据保持在一定的顺序(例如,hp,然后是atk,然后是def),在这种情况下,您不需要检查。但这可能最终会令人困惑。
https://stackoverflow.com/questions/25346062
复制相似问题