Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不一致的空指针异常_Java_Android_Json - Fatal编程技术网

Java 不一致的空指针异常

Java 不一致的空指针异常,java,android,json,Java,Android,Json,我正在尝试从设备外部目录读取.json文件 我有一个名为ExternalFile的类,用于读入文件并以字符串形式返回内容 下面是课堂: public class ExternalFile { final String EXTERNAL_STORAGE = Evironment.getExternalStorageDirectory().toString(); final String FIRSTDROID_DIRECTORY = EXTERNAL_STORAGE + "/firstdroid/"

我正在尝试从设备外部目录读取.json文件

我有一个名为ExternalFile的类,用于读入文件并以字符串形式返回内容

下面是课堂:

public class ExternalFile
{
final String EXTERNAL_STORAGE = Evironment.getExternalStorageDirectory().toString();
final String FIRSTDROID_DIRECTORY = EXTERNAL_STORAGE + "/firstdroid/";
final String SALES_DIRECTORY = FIRSTDROID_DIRECTORY + "sales/";
final String REFERENCE_DIRECTORY = FIRSTDROID_DIRECTORY + "reference/";

public String readFile(String direcectory, String fileName)
{
    BufferedReader br;
    StringBuilder sBuffer;
    File JSON;
    String line;
    String retVal = null;

    try
    {
        sBuffer = new StringBuilder();
        JSON = new File(direcectory, fileName);

        br = new BufferedReader(new FileReader(JSON));
        while ((line = br.readLine()) != null)
        {
            sBuffer.append(line);
            sBuffer.append('\n');
        }

        retVal = sBuffer.toString();

        Log.d("File Results: ", retVal);
    }
    catch (Exception e)
    {
        Log.e("readJSON", e.getMessage());
    }

    return retVal;
}
}

当我使用这个类读取“login.json”文件时,它工作得很好。但是,当我使用该类读取“contacts.json”文件时,eclipse警告: “空指针访问:变量readJSON只能在此位置为空”


唯一的区别是我传入了“contacts.json”而不是“login.json”

如果您使用变量而没有初始化它,Eclipse会发出警告。在代码中,声明了
readJSON
,但初始化为
null
。在这之后,它被用于
try
块中,这肯定会导致NPE

ExternalFile readJSON = null; //--> you have not intialized readJSON 
try
{
     result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json");
              ^^^^^^^^
              null access here

如果使用变量而未初始化它,Eclipse会发出警告。在代码中,声明了
readJSON
,但初始化为
null
。在这之后,它被用于
try
块中,这肯定会导致NPE

ExternalFile readJSON = null; //--> you have not intialized readJSON 
try
{
     result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json");
              ^^^^^^^^
              null access here