我正在尝试为我的程序实现登录功能,但它返回空指针异常。我知道当您引用内存中没有任何内容的位置时会发生这种情况,但据我所知,我已经正确实例化了所有对象 - 如果我错了请纠正我!
我正在尝试实现一个添加用户功能:我有一个用户名和密码列表,我有一个现有的方法可以读取该文件并将其存储在一个数组中。我想在列表中写一个新的登录名,所以我写了一个新方法,将这个数组转换为 ArrayList,最终会向它写一个新的登录名,然后再次写出登录文件。问题是我收到空指针异常。
方法一:
public String[] readFile(){
ArrayList<String> dataList = new ArrayList<String>();
String Line;
try {
String line = br.readLine();
do {
dataList.add(Line);
line = br.readLine();
}
while (!line.isEmpty());
br.close ();
}
catch (Exception e) {
e.printStackTrace();
}
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
return dataArr; // Returns an array containing the separate lines of the file
}
方法二:
public void addNewUser (String username, String password){
String[] dataArr = readFile(); // Read in the list of profiles and store it in an array
ArrayList<String> dataAL = new ArrayList<String>(Arrays.asList(dataArr)); // store array of profiles as ArrayList
dataAL.add(username + "\t" + password);
}
最佳答案
你可能在这里得到空指针
while (!line.isEmpty());
改成
while(line!=null && !line.isEmpty())
如果您注意异常的堆栈跟踪,您应该看到引发异常的确切行
关于java - 使用 isEmpty() 方法时获取空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8638440/