尝试使用File类加载文件时出现空指针异常

时间:2011-11-29 05:06:32

标签: java file nullpointerexception

我有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?

在setFile()方法argumnet中的

p.s,我在命令提示符的args [0]位置传入Details.dat

4 个答案:

答案 0 :(得分:3)

问题在于:

public class Details{
    private String path;
    File myFile = new File(path);
    ...

构造对象时将执行File myFile = new File(path)行。这意味着执行此行时path为空。

您应该更改代码,以便仅在需要时实例化File对象。

答案 1 :(得分:3)

首先初始化文件,然后设置文件路径。 尝试在Details类中使用构造函数:

public Details(String path)
        this.path = path;
        myFile = new File(path);
}

答案 2 :(得分:0)

public class Details{
   private  String path;
   File myFile =new File(path);
   ...

myFile如何将其路径设置为除""以外的任何其他内容?

答案 3 :(得分:0)

您正在尝试使用路径名创建File对象而不初始化路径。因为

File myFile = new File(path); 

行将在设置路径之前执行,并且此时它为空。所以先设置path的值,然后创建File的对象。