0

我正在尝试从设备外部目录中读取 .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 在此位置只能为空”。

    private void getContactNames()
{
    // File jsonCustomers;
    // BufferedReader br= null;
    // StringBuilder sb = null;
    // String line;
    String result;

    ExternalFile readJSON = null;

    try
    {
            result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json");

        // pass through the json string
        readNames(result, "contact");
    }
    catch (Exception e)
    {
        messageBox("getCustomerNames", e.toString());
    }
}

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

4

1 回答 1

5

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

ExternalFile readJSON = null; //--> you have not intialized readJSON 
try
{
     result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json");
              ^^^^^^^^
              null access here
于 2013-08-01T08:22:24.170 回答