我正在使用以下代码将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(线);
答案 0 :(得分:2)
我们有以下周期:
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);
。
答案 1 :(得分:1)
这是因为此时line
为空
看看循环:
while ((line = r.readLine()) != null) {
total.append(line);
}
当循环结束时,line
为空。
当您尝试运行以下代码时:
outputStreamWriter.write(line);
您将空值传递给write
方法。
java.io.Writer.write(String str)
实施如下:
write(str, 0, str.length());
在null对象上调用length()方法会导致NullPointerException。
答案 2 :(得分:1)
改变这个:
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
myContext.openFileOutput("settings.json", Context.MODE_PRIVATE));
outputStreamWriter.write(line);
outputStreamWriter.close();
到
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
myContext.openFileOutput("settings.json", Context.MODE_PRIVATE));
outputStreamWriter.write(total.toString());
outputStreamWriter.close();