0

Hello I am making a addon for bukkit a minecraft server modding program. This program requires me to put a jar into a foulder with an addon text document to provide class locations anyway. Then it uses my class and cast it into the class into the a class that it requires my class to inherit from. I am trying to write a text file in the same directory as my program so i wrote this(it is for a money program) (playerName is a pramater i used it as the filename because it is the player you are keeping balance for)

try{
    FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
    getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");
    writer = new BufferedWriter(fstream);
    writer.write("30");
    return 30;
}
catch(Exception err){
     getLogger().log(Level.INFO, "Exception occoured!{0}", err.getMessage());
     return -1;
}

when i try to read it with this code it throws an exception

BufferedReader reader = new BufferedReader(new FileReader(new File(".").getAbsolutePath()+"/"+playerName));
Integer i = Integer.getInteger(reader.readLine());
return i.intValue();

Also i cannot find the text document it suposedly wrote. Any advice? Also i would like to try to save it back a file so it is not saved in the .jar file but i dont know how to do that. Also is there a possibility it is saving the file in the folder that the program that is using the class? Thanks XD

4

1 回答 1

0

这是我很久以来看到的最奇怪的事情:

FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");

尝试清理:

File f=new File(playerName + ".txt");
FileWriter fstream = new FileWriter(f, true);
getLogger().log(Level.INFO,"trying to save text document to " + f.getAbsolutePath());

接下来的事情:你应该总是在使用 then 之后关闭文件。

那么你的文件名不匹配。一次它是playername+".txt"下一次它只是playername

但是最大的错误:

Integer i = Integer.getInteger(reader.readLine());
return i.intValue();

Integer.getInteger解析字符串。它将查找该名称的系统属性(您不会拥有名为 的系统属性"30")并将其解释为整数(如果存在)。在您的情况下,它将返回null,因此您NullPointerException在调用intValue它时会得到一个。改用Integer.parseInt

try(BufferedReader reader = new BufferedReader(new FileReader(playerName+".txt"))) {
  Integer i = Integer.parseInt(reader.readLine());
  return i.intValue();
}
于 2013-09-05T16:13:20.187 回答