java.io.StreamCorruptedException:错误的格式读取超过1对象时 [英] java.io.StreamCorruptedException: Wrong format when reading more than 1 object

查看:670
本文介绍了java.io.StreamCorruptedException:错误的格式读取超过1对象时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想补充( OneChatMessage 类的)一个对象插入每个按钮点击一个文件。然后我尝试读取该文件中的所有对象,并将其加载到一个的ArrayList 。但我得到一个 StreamCorruptedException ObjectInputStream.readObject()在反序列化功能的第二次迭代。我已经验证了第一次迭代工作正常。

我看了很多其他职位就同一问题:

  1. 在一个建议(反序列化多个Java对象)是编写整个数组列表中文件,而不是单个对象。但是,这似乎浪费了,因为我需要写上的每个按钮单击文件,将有上百个对象随着时间的推移。
  2. 在另一项建议(<一href="http://stackoverflow.com/questions/2393179/streamcorruptedexception-invalid-type-$c$c-ac">StreamCorruptedException:无效的类型code:AC )是做与ObjectOutputStream中创建不同的页眉。我不知道用这些知识谁解决问题。

我如何才能解决这个任何想法?

OneChatMessage.java:

 包com.slapp.chat;

的Bean;
进口java.util.Date;

进口com.slapp.localDB.Contact;

//这个类定义的类聊天信息
公共类OneChatMessage实现Serializable {
    私人字符串文本;
    私人日期timeSent;
    私人布尔sentByMe;

    公共OneChatMessage(字符串文本,日期timeSent,布尔sentByMe){
        this.text =文本;
        this.timeSent = timeSent;
        this.sentByMe = sentByMe;
    }

    公共字符串的getText(){
        返回this.text;
    }

    公开日期getTimeSent(){
        返回this.timeSent;
    }

    @覆盖
    公共字符串的toString(){
        返回新的StringBuffer(文本)
        .append(this.text)
        .append(TimeSent:)
        .append(this.timeSent.toString())//需要使用SimpleDatFormat得到正确的时区和格式。离开它了。
        .append(SentByMe:)
        。.append(this.sentByMe.toString())的toString();
    }
}
 

序列化功能:

 公共无效方法addMessage(OneChatMessage味精){
        FileOutputStream中FOS;
        ObjectOutputStream的OOS;

        档案文件=新的文件(context.getFilesDir(),ABC);
        如果(!file.exists()){
            Log.d(faizal
                    该文件不存在:);
        } 其他 {
            Log.d(faizal
                    文件已存在:);
        }
        尝试 {

            FOS = context.openFileOutput(ABC,
                    Context.MODE_APPEND);
            OOS =新的ObjectOutputStream(FOS);
            oos.writeObject(MSG);
            oos.close();
            fos.close();
        }赶上(FileNotFoundException异常E){
            Log.d(faizal,找不到文件);
            e.printStackTrace();
        }赶上(IOException异常E){
            Log.d(faizal,错误关闭文件:);
            e.printStackTrace();
        }
}
 

反序列化功能:

 公开的ArrayList&LT; OneChatMessage&GT; getAllChatMessagesArrayList(){
        ArrayList的&LT; OneChatMessage&GT; chatMessages =新的ArrayList&LT; OneChatMessage&GT;();
        OneChatMessage oneChatMsg;
        的FileInputStream FIS;
        ObjectInputStream的OIS;

        尝试 {

            FIS = context.openFileInput(ABC);
            OIS =新的ObjectInputStream(FIS);
            //设定一个任意大数量的循环迭代的极限
            //使聊天信息是从到EOF文件中读取
            的for(int i = 1; I&LT; 999999999;我++){
                尝试 {
                    oneChatMsg =(OneChatMessage)ois.readObject();
                }赶上(EOFException类发送){
                    //当EOFException类时,退出循环
                    打破;
                }

                尝试{
                    chatMessages.add(oneChatMsg);
                }赶上(例外五){
                    Log.d(faizal,错误将消息发送到数组列表:+ oneChatMsg.getText());
                    e.printStackTrace();
                }


            }
            ois.close();
            fis.close();

            返回chatMessages;
        }赶上(FileNotFoundException异常E){
            Log.d(faizal,文件未找到);
            e.printStackTrace();
        }赶上(IOException异常E){
            Log.d(faizal,错误关闭文件:);
            e.printStackTrace();
        }赶上(ClassNotFoundException异常E){
            Log.d(faizal,从文件读取错误的对象:);
            e.printStackTrace();
        }赶上(UnsupportedOperationException异常E){
            Log.d(faizal,错误添加对象数组列表的文件:);
            e.printStackTrace();
        }
        返回null; //如果有一个捕获的异常

    }
 

logcat的:

  05-27 16:56:17.576:W / System.err的(25028):java.io.StreamCorruptedException:错误的格式:AC
05-27 16:56:17.576:W / System.err的(25028):在java.io.ObjectInputStream.corruptStream(ObjectInputStream.java:701)
05-27 16:56:17.576:W / System.err的(25028):在java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:814)
05-27 16:56:17.576:W / System.err的(25028):在java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
05-27 16:56:17.576:W / System.err的(25028):在java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
05-27 16:56:17.576:W / System.err的(25028):在com.slapp.chat.ChatPersistenceHandler.getAllChatMessagesArrayList(ChatPersistenceHandler.java:62)
05-27 16:56:17.576:W / System.err的(25028):在com.example.slapp.ChatSessionActivity $ ChatArrayAdapter&LT; INIT&GT;(ChatSessionActivity.java:178)
05-27 16:56:17.576:W / System.err的(25028):在com.example.slapp.ChatSessionActivity.onCreate(ChatSessionActivity.java:86)
05-27 16:56:17.576:W / System.err的(25028):在android.app.Activity.performCreate(Activity.java:5372)
05-27 16:56:17.576:W / System.err的(25028):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-27 16:56:17.576:W / System.err的(25028):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
05-27 16:56:17.576:W / System.err的(25028):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
05-27 16:56:17.576:W / System.err的(25028):在android.app.ActivityThread.access $ 700(ActivityThread.java:168)
05-27 16:56:17.576:W / System.err的(25028):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1329)
05-27 16:56:17.576:W / System.err的(25028):在android.os.Handler.dispatchMessage(Handler.java:99)
05-27 16:56:17.576:W / System.err的(25028):在android.os.Looper.loop(Looper.java:137)
05-27 16:56:17.576:W / System.err的(25028):在android.app.ActivityThread.main(ActivityThread.java:5493)
05-27 16:56:17.576:W / System.err的(25028):在java.lang.reflect.Method.invokeNative(本机方法)
05-27 16:56:17.576:W / System.err的(25028):在java.lang.reflect.Method.invoke(Method.java:525)
05-27 16:56:17.576:W / System.err的(25028):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-27 16:56:17.576:W / System.err的(25028):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-27 16:56:17.576:W / System.err的(25028):在dalvik.system.NativeStart.main(本机方法)
 

解决方案

追加到一个ObjectOutputStream不起作用开箱即用,因为它会创建多个标题,如在<一个描述href="http://stackoverflow.com/questions/2393179/streamcorruptedexception-invalid-type-$c$c-ac">StreamCorruptedException:无效的类型code:AC

请参阅追加到一个ObjectOutputStream 一个解决方案。

I am trying to add an object( of OneChatMessage class) into a file on every button click. And then i try to read all the objects from the file and load it into a ArrayList. But i get a StreamCorruptedException at the second iteration of ObjectInputStream.readObject() in the deserialization function. I have verified that the first iteration works fine.

I have read many other posts on the same issue :

  1. One suggestion(Deserialize multiple Java Objects) is to write the entire array list to the file instead of individual objects. But that seems wasteful, as i need to write to file on every button click and there would be hundreds of objects over time.
  2. Another suggestion(StreamCorruptedException: invalid type code: AC) is to do with different headers created by ObjectOutputStream. I have no idea who to use this knowledge to resolve the issue.

Any idea on how i can resolve this?

OneChatMessage.java :

package com.slapp.chat;

import java.io.Serializable;
import java.util.Date;

import com.slapp.localDB.Contact;

//This class defines the class for a chat message
public class OneChatMessage implements Serializable{
    private String text;
    private Date timeSent;
    private Boolean sentByMe;

    public OneChatMessage(String text, Date timeSent, Boolean sentByMe){
        this.text = text;
        this.timeSent = timeSent;
        this.sentByMe = sentByMe;
    }

    public String getText(){
        return this.text;
    }

    public Date getTimeSent(){
        return this.timeSent;
    }

    @Override
    public String toString(){
        return new StringBuffer(" Text : ")
        .append(this.text)
        .append(" TimeSent : ")
        .append(this.timeSent.toString()) // Need to use SimpleDatFormat to get the correct time zone and formatting. Leaving it for now.
        .append(" SentByMe : ")
        .append(this.sentByMe.toString()).toString();
    }
}

Serializing function :

public void addMessage(OneChatMessage msg) {
        FileOutputStream fos;
        ObjectOutputStream oos;

        File file = new File(context.getFilesDir(), "abc");
        if (!file.exists()) {
            Log.d("faizal",
                    "The file does not exist : ");
        } else {
            Log.d("faizal",
                    "The file already exists : ");
        }
        try {

            fos = context.openFileOutput("abc",
                    Context.MODE_APPEND);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(msg);
            oos.close();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("faizal", "file not found : ");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("faizal", "Error closing file : ");
            e.printStackTrace();
        }
}

Deserializing function :

public ArrayList<OneChatMessage> getAllChatMessagesArrayList() {
        ArrayList<OneChatMessage> chatMessages = new ArrayList<OneChatMessage>();
        OneChatMessage oneChatMsg;
        FileInputStream fis;
        ObjectInputStream ois;

        try {

            fis = context.openFileInput("abc");
            ois = new ObjectInputStream(fis);
            //Setting an arbitrarily large number as the limit of the loop iterations
            //so that chat message are read from the file till EOF
            for (int i = 1; i < 999999999; i++) {
                try {
                    oneChatMsg = (OneChatMessage) ois.readObject();
                } catch (EOFException e) {
                    //When EOFException occurs, quit the loop
                    break;
                }

                try{
                    chatMessages.add(oneChatMsg);
                } catch(Exception e){
                    Log.d("faizal","Error adding message to Array List:" + oneChatMsg.getText());
                    e.printStackTrace();
                }


            }
            ois.close();
            fis.close();

            return chatMessages;
        } catch (FileNotFoundException e) {
            Log.d("faizal", "The file not found : ");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("faizal", "Error closing file : ");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            Log.d("faizal","Error reading object from file : ");
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            Log.d("faizal", "Error adding object to array list from file : ");
            e.printStackTrace();
        }
        return null; // in case there was a caught exception

    }

Logcat :

05-27 16:56:17.576: W/System.err(25028): java.io.StreamCorruptedException: Wrong format: ac
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.corruptStream(ObjectInputStream.java:701)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:814)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
05-27 16:56:17.576: W/System.err(25028):    at com.slapp.chat.ChatPersistenceHandler.getAllChatMessagesArrayList(ChatPersistenceHandler.java:62)
05-27 16:56:17.576: W/System.err(25028):    at com.example.slapp.ChatSessionActivity$ChatArrayAdapter.<init>(ChatSessionActivity.java:178)
05-27 16:56:17.576: W/System.err(25028):    at com.example.slapp.ChatSessionActivity.onCreate(ChatSessionActivity.java:86)
05-27 16:56:17.576: W/System.err(25028):    at android.app.Activity.performCreate(Activity.java:5372)
05-27 16:56:17.576: W/System.err(25028):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.access$700(ActivityThread.java:168)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
05-27 16:56:17.576: W/System.err(25028):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 16:56:17.576: W/System.err(25028):    at android.os.Looper.loop(Looper.java:137)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.main(ActivityThread.java:5493)
05-27 16:56:17.576: W/System.err(25028):    at java.lang.reflect.Method.invokeNative(Native Method)
05-27 16:56:17.576: W/System.err(25028):    at java.lang.reflect.Method.invoke(Method.java:525)
05-27 16:56:17.576: W/System.err(25028):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-27 16:56:17.576: W/System.err(25028):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-27 16:56:17.576: W/System.err(25028):    at dalvik.system.NativeStart.main(Native Method)

解决方案

Appending to an ObjectOutputStream doesn't work out of the box as it creates multiple headers as described in StreamCorruptedException: invalid type code: AC.

See Appending to an ObjectOutputStream for a solution.

这篇关于java.io.StreamCorruptedException:错误的格式读取超过1对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆