简体   繁体   English

尝试将文件写入内部数据时不断获取NullPointerException

[英]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: 我正在使用以下代码将json文件从我的资产文件夹复制到数据文件夹,以便在首次启动时使用此数据,直到加载了真实数据为止:

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); outputStreamWriter.write(line);

We have a following cycle: 我们有以下周期:

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

So, obviously, line equals to null in the end of it. 因此,很显然, line末尾等于null Now, let's take a look at Writer#write(String) implementation. 现在,让我们看一下Writer#write(String)的实现。 It invokes 3-argument version of the write() function which looks like so: 它调用write()函数的3参数版本,如下所示:

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 . 如果strnullstr.length()将失败,并出现NullPointerException

I think what you need is outputStreamWriter.write(total.toString()); 我认为您需要的是outputStreamWriter.write(total.toString()); , not the outputStreamWriter.write(line); ,而不是outputStreamWriter.write(line); .

It's because line is null at that point. 这是因为line在那一点上为空。
Look at the loop: 看一下循环:
while ((line = r.readLine()) != null) { total.append(line); }
When the loop is over, line is null. 循环结束后, line为null。 When you're then trying to run following code: 当您尝试运行以下代码时:
outputStreamWriter.write(line); you are passing null value to the write method. 您正在将null值传递给write方法。
java.io.Writer.write(String str) implementation is following: java.io.Writer.write(String str)实现如下:
write(str, 0, str.length());

The invocation of length() method on null object cause NullPointerException. 在null对象上调用length()方法会导致NullPointerException。

change this: 改变这个:

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    myContext.openFileOutput("settings.json", Context.MODE_PRIVATE));
            outputStreamWriter.write(line);
            outputStreamWriter.close();

to

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    myContext.openFileOutput("settings.json", Context.MODE_PRIVATE));
            outputStreamWriter.write(total.toString());
            outputStreamWriter.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试写入文件时出现NullPointerException - NullPointerException when trying to write to file 尝试检索Spring bean,但不断获取NullPointerException - Trying to retrieve Spring bean but keep getting a NullPointerException 为什么我在尝试读取文件时收到 NullPointerException? - Why am I getting a NullPointerException when trying to read a file? 尝试在Java中打开图像文件时获取NullPointerException - Getting a NullPointerException when trying to open an image file in java 尝试使用 Selenium 从 Excel 文件读取数据时出现 NullPointerException - NullPointerException when trying to read data from Excel file using Selenium onPause()NullPointerException-尝试将数据写入数据库onPause - onPause() NullPointerException - trying to write data to database onPause 将数据写入内部文件 - ContextWrapper NullPointerException - Writing Data to Internal File - ContextWrapper NullPointerException 尝试将对象实例写入ObjectOutputStream时发生NullPointerException - NullPointerException when trying to write object instance to ObjectOutputStream 尝试在 JAVA 中将数据写入多个工作表时,XLSX 文件损坏 - XLSX file getting corrupted when trying to write data into multiple sheets in JAVA 尝试在Android中打开Excel文件时不断收到FileNotFound异常 - Keep getting FileNotFound Exception when trying to open an excel file in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM