title: Serialize data and write to a file
body: <p>I am facing this error when I try to write objects to a file. </p>
  
  <pre><code>02-05 11:31:41.818: W/System.err(2414): java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[], int, int)' on a null object reference
  02-05 11:31:41.818: W/System.err(2414):     at java.io.DataOutputStream.writeShort(DataOutputStream.java:192)
  02-05 11:31:41.818: W/System.err(2414):     at java.io.ObjectOutputStream.writeStreamHeader(ObjectOutputStream.java:1795)
  02-05 11:31:41.818: W/System.err(2414):     at java.io.ObjectOutputStream.&lt;init&gt;(ObjectOutputStream.java:271)
  02-05 11:31:41.818: W/System.err(2414):     at com.data.mydata.addData(addData.java:173)
  </code></pre>
  
  <p>The line 173 which shows the error is <code>oos = new ObjectOutputStream(fileStream);</code></p>
  
  <p>My code is - </p>
  
  <pre><code>path = Environment.getExternalStorageDirectory()
                      + File.separator + "Documents";
  
          path += File.separatorChar + "Sensor Data";
          Log.d("hi", "path = " + path);
          File file = new File(path, filename);
  
          new File(path).mkdirs();
          try {
              file.createNewFile();
                          fileStream = new FileOutputStream(filename);
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
  </code></pre>
  
  <p>//AllData extends Serializable</p>
  
  <pre><code>List&lt;AllData&gt;valuelist = new ArrayList&lt;AllData&gt;(sensor.values());
  
  if(valuelist.size() != 5){
                  try {
                      //fileStream = new FileOutputStream(filename);
                      oos = new ObjectOutputStream(fileStream);
                      oos.writeObject(valuelist);
  
                  } catch (Exception e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }else{
                  try {
                      oos.close();
                  } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
  </code></pre>
  
  <p>Basically when my size of arraylist is not equal to 5, I need to keep writing to the file and once its 5, I need to stop it. My file is created properly in SDCard in Documents/Sensor Data/myfile.txt . Could you please help me how do I resolve this error?</p>