序列化数据并写入文件

时间:2016-02-05 10:45:16

标签: java android

当我尝试将对象写入文件时,我遇到此错误。

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.<init>(ObjectOutputStream.java:271)
02-05 11:31:41.818: W/System.err(2414):     at com.data.mydata.addData(addData.java:173)

显示错误的第173行是oos = new ObjectOutputStream(fileStream);

我的代码是 -

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();
        }
    }

// AllData扩展Serializable

List<AllData>valuelist = new ArrayList<AllData>(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();
                }
            }

基本上当我的arraylist大小不等于5时,我需要继续写入文件,一旦它的5,我需要停止它。我的文件在Document / Sensor Data / myfile.txt中的SDCard中正确创建。你能帮我解决一下这个错误吗?

1 个答案:

答案 0 :(得分:1)

从错误中可以看出valuelist的某些元素为空。 做点什么

         try {
                //fileStream = new FileOutputStream(filename);
                oos = new ObjectOutputStream(fileStream);
               + List<AllData> nonNullList = new ArrayLis<>();
               + for(AllData aData: valuelist)
               +    if(aData != null) nonNullList.add(aData);
               + oos.writeObject(nonNullList);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

当然,如果你的条件list == 5元素需要总是写5个元素,那么这个空消除列表应该代替

   if(valuelist.size() != 5){