我发布了一个应用程序,我需要将一些hunderd kb size ogg文件复制到用户的SD卡上。很快我收到了错误报告。就我而言,问题可能是因为该路径不适合该特定电话:
String path = "/sdcard/file.ogg";
File file = new File(Environment.getExternalStorageDirectory(), "file.ogg" );
if (!file.exists()) {
InputStream in = getResources().openRawResource(R.raw.file);
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
所以报告是:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.caodeveloping.androgangnam/com.caodeveloping.androgangnam.Main}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.caodeveloping.androgangnam.Main.onCreate(Main.java:388)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
... 11 more
第388行是out.close();是否有可能/ sdcard /不适合该手机上的路径?什么可能导致这个?提前谢谢!
更新,这个?
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
path += "/file.ogg";
答案 0 :(得分:1)
两个问题:
a)显然,如果你无法打开它,你试图关闭文件(out.close()),事件
b)我建议使用Environment.getExternalStorageDirectory(),而不是硬编码目录名“/ sdcard”。无法保证将SD卡安装到此路径。这正是Environment.getExternalStorageDirectory()API的原因。
另外,我建议查看整个代码以进行错误处理(如果无法打开,读取等内容)