所以我有这个Void函数,假设从.txt文件中读取整数,它大部分都有效,除了它只读取前两行我尝试过的所有内容都没有用,似乎没有任何工作
public static void load(Player p) {
String line = "";
String token = "";
String token2 = "";
String[] token3 = new String[3];
boolean EndOfFile = false;
BufferedReader characterfile = null;
boolean File1 = false;
try {
characterfile = new BufferedReader(new FileReader("./cache/Player.txt"));
File1 = true;
} catch (FileNotFoundException fileex1) {
}
if (File1) {
// new File ("./characters/"+playerName+".txt");
} else {
System.out.println("character file not found.");
}
try {
line = characterfile.readLine();
} catch (IOException ioexception) {
System.out.println(": error loading file.");
}
while (EndOfFile == false && line != null) {
line = line.trim();
int spot = line.indexOf("=");
if (spot > -1) {
token = line.substring(0, spot);
token = token.trim();
token2 = line.substring(spot + 1);
token2 = token2.trim();
token3 = token2.split("\t");
if (token.equals("Difficulty")) {
Player.setDifficulty(Integer.parseInt(token2));
}
else if (token.equals("Player Health")) {
//System.out.println(token2);
System.out.println("debug");
Player.setHealth(Integer.parseInt(token2));
}
else if (token.equals("Player Strength")) {
//System.out.println(token2);
Player.setStrength(Integer.parseInt(token2));
}
try {
line = characterfile.readLine();
} catch (IOException ioexception1) {
System.out.println("sent");
EndOfFile = true;
}
}
try {
characterfile.close();
} catch (IOException ioexception) {
}
}
}
这是我的保存方法,按预期运行。
public void save(Player p) {
BufferedWriter characterfile = null;
try {
characterfile = new BufferedWriter(new FileWriter("./cache/Player.txt"));
characterfile.write("Player Strength = ");
characterfile.write(Integer.toString(Player.getStrength()));
characterfile.newLine();
characterfile.write("Player Health = ");
characterfile.write(Integer.toString(Player.getHealth()));
characterfile.newLine();
characterfile.write("Difficulty = ");
characterfile.write(Integer.toString(Player.getDifficulty()));
characterfile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是我的Player.txt看起来像
Player Strength = 0
Player Health = 0
Difficulty = 0
再次,因为我说玩家力量和球员健康将被阅读,但然后令牌甚至不会去困难或完全跳过它,我完全没有想法。
答案 0 :(得分:1)
拨打br.readLine()
只能一次读取一行。您可以循环直到br.readLine()
不返回null
。
String line=null;
while((line=br.readLine())!=null){
//Do your stuff
}
答案 1 :(得分:0)
您在while循环中关闭文件。
移动这些行:
try {
characterfile.close();
} catch (IOException ioexception) {
}
添加一个`}'在行之前删除一行。
答案 2 :(得分:0)
你在循环中调用characterfile.close();
。这应该在你的循环之外(while (EndOfFile == false && line != null) { ...}
)。第一个循环工作,但你关闭你的文件,第二个循环你得到IOException,因为你试图读取你的已关闭文件。