【问题标题】:Why am I getting NullPointerException? bufferWriter.close()为什么我会收到 NullPointerException? bufferWriter.close()
【发布时间】:2015-11-22 14:51:07
【问题描述】:

我是新手,但我正在编写一个应用程序,但我不断收到此错误,导致应用程序在启动时崩溃。

java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference

导致它的代码在下面的类中,问题所在的行旁边会有一个 HERE 注释。

public class FileOptions extends Activity{

public void createFile(String title, String storeValue){
    BufferedWriter bufferWriter = null;
    try {
        FileOutputStream fileOutputStream = openFileOutput(title, Context.MODE_PRIVATE);
        bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

        String content = storeValue;

        bufferWriter.write(content);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {  //Cannot be removed
        e.printStackTrace();
    }
    finally {
        try {
       /**HERE*/ bufferWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
//More unimportant stuff
}

这是我从中调用方法的代码。

public class MainActivity extends ActionBarActivity {
Context context = this;
boolean debug = true;
FileOptions file = new FileOptions();
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getBoolean("isfirstrun", true);

    if(isFirstRun) {
        file.createFile("userInfo", "");
        getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
                .putBoolean("isfirstrun", false).commit();
    }

    if(file.readFile("userInfo") != "")
    {
        if(debug){alerter(file.readFile("userInfo"));alerter("true");}
        switchToHome();
    }else{
        if(debug){alerter("false");}
    }
}
}

这是堆栈跟踪。

08-27 22:44:35.830  13089-13089/? I/libpersona﹕ KNOX_SDCARD checking this for 10247

08-27 22:44:35.830  13089-13089/? I/libpersona﹕ KNOX_SDCARD not a persona

08-27 22:44:35.830  13089-13089/? E/Zygote﹕ MountEmulatedStorage()

08-27 22:44:35.830  13089-13089/? E/Zygote﹕ v2

08-27 22:44:35.830  13089-13089/? I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SM-N910V_5.0.1 ver=27

08-27 22:44:35.830  13089-13089/? I/SELinux﹕ Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_SM-N910V_5.0.1_0027

08-27 22:44:35.830  13089-13089/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL

08-27 22:44:35.830  13089-13089/? I/art﹕ Late-enabling -Xcheck:jni

08-27 22:44:35.870  13089-13089/? D/TimaKeyStoreProvider﹕ TimaSignature is unavailable

08-27 22:44:35.870  13089-13089/? D/ActivityThread﹕ Added TimaKeyStore provider

08-27 22:44:35.920  13089-13089/? D/ResourcesManager﹕ creating new AssetManager 
and set to /data/app/preventioninnovations.preventapp-2/base.apk

08-27 22:44:36.050  13089-13089/? D/AndroidRuntime﹕ Shutting down VM

08-27 22:44:36.050  13089-13089/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: preventioninnovations.preventapp, PID: 13089
    java.lang.RuntimeException: Unable to start activity ComponentInfo{preventioninnovations.preventapp/preventioninnovations.preventapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2712)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777)
            at android.app.ActivityThread.access$900(ActivityThread.java:179)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5972)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference
            at preventioninnovations.preventapp.FileOptions.createFile(FileOptions.java:37)
            at preventioninnovations.preventapp.MainActivity.onCreate(MainActivity.java:38)
            at android.app.Activity.performCreate(Activity.java:6289)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777)
            at android.app.ActivityThread.access$900(ActivityThread.java:179)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5972)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)

感谢您的帮助。

【问题讨论】:

  • 看看你的堆栈跟踪会很有帮助
  • 在调用 bufferWriter.close() 之前检查它是否不为空。如果为null,则不能调用返回NPE的.close()。
  • 可能类似,但我觉得代码不同,问一个新问题是可以的。
  • 好吧,如果我不将它分成一个类,那么相同的代码也可以工作,所以我想这就是我要做的。我意识到您可以检查它是否为空,但它不会创建所需的文件(我认为?)

标签: java android


【解决方案1】:

当您的 openFileOutput() 方法抛出异常时会发生这种情况。

由于抛出异常,bufferWriter 未初始化为有效对象。

并且异常导致执行跳过try块的其余部分去catch块然后finally块。

所以,当它到达 finally 块时,bufferWriternull

finally {
        try {
            if (bufferWriter != null)
                bufferWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

要解决此问题,请在 bufferWriter 中调用 close 之前检查 null

或者更好地使用尝试资源

try(BufferedWriter = new BufferedWriter(
                         new OutputStreamWriter(
                             openFileOutput(title, Context.MODE_PRIVATE)))) {}

【讨论】:

    【解决方案2】:
    finally {
        if(bufferWriter!=null){
            bufferWriter.close();/**HERE*/
        }
    }
    

    看起来你的 bufferWriter 是空的。所以也许你给它的文件不起作用?如果 bufferwriter 为空,这将停止 NPE。

    【讨论】:

      【解决方案3】:

      Java 7 为 try-catch 块提供了更简洁的界面。

      您可以阅读更多关于替代方法的信息from this SO answer

      public void createFile(String title, String storeValue){
          try (
              FileOutputStream fileOutputStream = openFileOutput(title, Context.MODE_PRIVATE);
              BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream))
          ) {
              String content = storeValue;
              bufferWriter.write(content);
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          }
      }
      

      【讨论】:

        【解决方案4】:

        发现问题。我需要将我调用的类的上下文传递给方法以使其工作。

        我有:file.createFile("userInfo", "");,我需要:file.createFile("userInfo", "", this);

        然后在我的方法中:

        public void createFile(String title, String storeValue){
            BufferedWriter bufferWriter = null;
            try {
                FileOutputStream fileOutputStream = openFileOutput(title, context.MODE_PRIVATE);
                bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
        

        我需要的地方:

        public void createFile(String title, String storeValue, /** ADDED */Context context){
            BufferedWriter bufferWriter = null;
            try {
                FileOutputStream fileOutputStream = /** CHANGE IS HERE */ context.openFileOutput(title, context.MODE_PRIVATE);
                bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-27
          • 1970-01-01
          • 1970-01-01
          • 2017-06-19
          相关资源
          最近更新 更多