从单独的类将文件写入内部存储时出现null异常

时间:2015-06-25 15:49:02

标签: android

我有两个活动,我想调用时间类,但每次我调用该类时都会引发异常。但是如果我将timeWrite()方法放在Activity中它运行良好但是如果我把它放在时间类中然后尝试调用它来编写文件它会抛出异常。

public class time extends AlphabetActivity{
      private int time;
      public void timeWrite(int time) {

       try {
          String timeVal = String.valueOf(time);
          FileOutputStream timeStream = openFileOutput("time_file.txt",    Context.MODE_PRIVATE);
        timeStream.write(timeVal.getBytes());}
        timeStream.close();
       catch (Exception e) {
        e.printStackTrace();}}

继承似乎有问题,我只是不明白我做错了什么。

1 个答案:

答案 0 :(得分:0)

   try {
      String timeVal = String.valueOf(time);
      FileOutputStream timeStream = openFileOutput("time_file.txt",    Context.MODE_PRIVATE);
    timeStream.write(timeVal.getBytes());
}
    timeStream.close();
   catch (Exception e) {
    e.printStackTrace();}
}

如果您写下代码,您的代码将被编译:

 try {
  String timeVal = String.valueOf(time);
  FileOutputStream timeStream = openFileOutput("time_file.txt",    Context.MODE_PRIVATE);
      timeStream.write(timeVal.getBytes());
      timeStream.close();
     }catch (Exception e) {
      e.printStackTrace();
    }

如果认为这个sytanx错了,这段代码是否编译? 我知道,请阅读此内容,但您必须现在或以后学习: https://docs.oracle.com/javase/tutorial/essential/exceptions/

相同 http://www.tutorialspoint.com/java/java_exceptions.htm

如果您将文件写入外部存储库,请注意向清单添加READ和WRITE_EXTERNAL_STORAGE权限