[英]null pointer exception while trying to load file using the File class
我有2個文件Details.java和TestDetails.java和一個名為Details.dat的數據文件
Details.java
import java.util.Scanner;
import java.io.*;
public class Details {
private String path;
File myFile = new File(path);
public void setMyFile(String path) {
this.path = path;
}
public void load() throws IOException, FileNotFoundException {
Scanner input = new Scanner(myFile);
int numberOfMembers = input.nextInt();
String[] members = new String[numberOfMembers];
for (String s : members) {
String name = input.next();
String age = input.next();
String qualification = input.next();
System.out.println("The name of the family member is " + name + " the age of the family member is" + age
+ " the qualification of the " + "family member is" + qualification);
}
}
}
TestDetails.java
import java.io.IOException;
public class TestDetails {
public static void main(String[] args) {
Details myDetails = new Details();
myDetails.setMyFile(args[0]);
try {
myDetails.load();
} catch (IOException i) {
System.out.println(i.getMessage());
}
}
}
Details.dat
4
a 26 bsc
b 22 bcom
c 50 ba
d 60 bsc
每當我試圖運行TestDetails.java文件我得到一個NullPointerException異常和堆棧跟蹤點指向File對象的堆棧跟蹤。
那么這是什么問題呢? 為什么我會收到NullPointerException?
ps在setFile()方法argumnet中,我在命令提示符下的args [0]位置傳遞了Details.dat
問題是這樣的:
public class Details{
private String path;
File myFile = new File(path);
...
構造對象時,將執行File myFile = new File(path)
行。 這意味着, path
為空,在執行該行的時間。
從而使你應該改變你的代碼File
,只有當你需要它的對象實例化。
您首先初始化文件,然后再設置文件路徑。 嘗試在Details類中使用構造函數:
public Details(String path)
this.path = path;
myFile = new File(path);
}
public class Details{
private String path;
File myFile =new File(path);
...
myFile
如何將其路徑設置為除""
以外的其他值?
您試圖使用路徑名創建File對象而不初始化路徑。 因為
File myFile = new File(path);
行將在設置路徑之前執行,此時為null。 因此,首先設置path的值,然后將其作為File的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.