我有一个方法:
private boolean canFileOpen(String fileName) {
boolean canOpen = true;
try {
InputStream test = openFileInput(fileName);
}
catch(FileNotFoundException e)
{
canOpen = false;
}
catch (IOException e)
{
canOpen = false;
}
return canOpen;
}
无论我传入fileName,应用程序只是说"应用程序已停止工作"并关闭。例如,我将传入" test.txt"即使它不存在,它也不应该使程序崩溃。我在这里做错了什么?
编辑:这是日志:
10-23 17:57:22.564 1476-1476/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cloneeskimo.simplefile/com.cloneeskimo.simplefile.activity_fileeditor}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.ContextImpl.makeFilename(ContextImpl.java:2005)
at android.app.ContextImpl.openFileInput(ContextImpl.java:709)
at android.content.ContextWrapper.openFileInput(ContextWrapper.java:173)
at com.cloneeskimo.simplefile.activity_fileeditor.canFileOpen(activity_fileeditor.java:49)
at com.cloneeskimo.simplefile.activity_fileeditor.initSystems(activity_fileeditor.java:32)
at com.cloneeskimo.simplefile.activity_fileeditor.onCreate(activity_fileeditor.java:41)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
fileName
为null
,基于您的堆栈跟踪,并基于makeFilename()
in ContextImpl
的当前实施。
答案 1 :(得分:0)
您正在捕获FileNotFoundException和IOException,并且您的堆栈跟踪清楚地表明您正在获取NullPointerException。
您没有捕获该异常,因此您的应用程序崩溃了。