Search code examples
javaandroidnullpointerexceptionwriter

Keep getting NullPointerException when trying to write file to internal data


I am using the following code to copy a json file from my assets folder to the data folder to use this data at first startup until the real data has loaded:

AssetManager am = myContext.getAssets();
        InputStream is = null;
        try {
            is = am.open("settings.json");
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        StringBuilder total = new StringBuilder();
        String line = "";
        try {
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    myContext.openFileOutput("settings.json", Context.MODE_PRIVATE));
            outputStreamWriter.write(line);
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e("Test", "File write failed: " + e.toString());
        }

But I keep getting the following error:

06-08 14:07:24.576: E/AndroidRuntime(10509): Caused by: java.lang.NullPointerException
06-08 14:07:24.576: E/AndroidRuntime(10509):    at     java.io.Writer.write(Writer.java:141)
06-08 14:07:24.576: E/AndroidRuntime(10509):    at     com.test.app.MainActivity.onCreate(MainActivity.java:370)
06-08 14:07:24.576: E/AndroidRuntime(10509):    at     android.app.Activity.performCreate(Activity.java:5243)
06-08 14:07:24.576: E/AndroidRuntime(10509):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

Which is this line:

outputStreamWriter.write(line);


Solution

  • We have a following cycle:

    while ((line = r.readLine()) != null) {
        total.append(line);
    }
    

    So, obviously, line equals to null in the end of it. Now, let's take a look at Writer#write(String) implementation. It invokes 3-argument version of the write() function which looks like so:

    public void write(String str, int offset, int count) throws IOException {
        if ((offset | count) < 0 || offset > str.length() - count) {
            throw new StringIndexOutOfBoundsException(str, offset, count);
        }
        char[] buf = new char[count];
        str.getChars(offset, offset + count, buf, 0);
        synchronized (lock) {
            write(buf, 0, buf.length);
        }
    }
    

    If str is null then str.length() will fail with NullPointerException.

    I think what you need is outputStreamWriter.write(total.toString());, not the outputStreamWriter.write(line);.