我使用以下代码将 json 文件从 Assets 文件夹复制到数据文件夹,以便在首次启动时使用此数据,直到加载实际数据:
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());
}
但我不断收到以下错误:
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)
这是哪一行:
outputStreamWriter.write(line);
最佳答案
我们有以下循环:
while ((line = r.readLine()) != null) {
total.append(line);
}
因此,显然,line
等于其末尾的 null
。现在,我们来看看Writer#write(String)执行。它调用 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);
}
}
如果 str
为 null
,则 str.length()
将失败并出现 NullPointerException
。
我认为您需要的是outputStreamWriter.write(total.toString());
,而不是outputStreamWriter.write(line);
。
关于java - 尝试将文件写入内部数据时不断出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106024/