我试图读取文件,但始终收到NullPointerException。有人知道可能是什么问题吗?我在java.io.Reader,java.io.BufferedReader,elte.hu.eltecom.file.FileManager.readGraph和elte.hu.eltecom.Main.main
处获得NullPointerExceptionpublic static void main(String[] args) {
// if (args.length == 0) return;
FileManager fm = new FileManager();
Manager manager;
manager = fm.readGraph("szia");
User user = manager.getUserById(3);
if (user instanceof AdminUser){
((AdminUser) user).kickUser(manager.getUserById(1));
((AdminUser) user).kickUser(manager.getUserById(2));
User grabowski = new User("Grabowski", Language.HUN);
manager.createUser(grabowski);
manager.linkUsers(grabowski,user);
}
fm.writeGraph(manager,args[0]);
}
static public Manager readGraph(String s) {
FileReader fr = null;
try {
fr = new FileReader(s + "/input.txt");
} catch (FileNotFoundException e) {
}
BufferedReader br = null;
br = new BufferedReader(fr);
String sCurrentLine = null;
try {
sCurrentLine = br.readLine();
} catch (IOException e) {
}
int x = Integer.parseInt(sCurrentLine);
Graph graph = null;
graph = initGraph(x);
Manager manager = null;
manager = new Manager(graph);
int temp = 0;
boolean lineLeft = true;
try {
sCurrentLine = br.readLine();
} catch (IOException e) {
}
User users[] = new User[x];
while(lineLeft){
if (temp < x){
String line[] = sCurrentLine.split(" ", 2);
Language language = Language.valueOf(line[0]);
User user;
String name = line[1];
if (line[1].contains("#")){
name = name.substring(1);
user= manager.createAdminUser(name, language);
}
else{
user = manager.createUser(name, language);
}
users[temp] = user;
}
else {
String line[] = sCurrentLine.split(" ");
for (int i = 0; i < line.length ; i++){
if (Boolean.valueOf(line[i])){
graph.linkNodes(users[temp-x], users[i]);
}
}
}
try {
if ( (sCurrentLine = br.readLine()) == null)
lineLeft = false;
} catch (IOException e) {
}
temp++;
}
return manager;
}
}
答案 0 :(得分:0)
看这里:
try {
fr = new FileReader(s + "/input.txt");
} catch (FileNotFoundException e) {
}
您刚刚写道:“读取文件“无论如何”,如果找不到该文件,则忽略它。
此时fr
为空,您将其作为输入传递给BufferedReader
而不检查其是否为空。
要么在实例化BufferedReader
之前写一个空检查,要么在找不到该文件的情况下执行其他操作。
以这种方式忽略异常非常危险,您的代码也不可靠。
另一个建议,String s
的可读性很差,尝试给出更好的名称(path
或appDir
或其他使读者易于理解的名称,而无需返回阅读完整代码)。