Android readObject异常,无法将String转换为ObjectStreamClass

时间:2013-12-15 00:26:44

标签: java android bufferedreader fileinputstream objectinputstream

我正在研究一个远程加载数据的android项目,将其保存到数组中(如果数据是新的),将其作为序列化文件写入磁盘,然后从磁盘读取它以加载ArrayList。

有时,ArrayList会填充数据,有时它不会填充,程序会崩溃。

我收到一个运行时异常,说明:java.land.ClassCastException:java.lang.String无法强制转换为java.io.ObjectStreamClass。

有时我也会收到java.io.StreamCorruptedException,有时我会收到和EOFException。

通过异常树,它似乎源于此调用:

personsArray = (ArrayList<Person>) in.readObject();

现在,有时数据加载正常没有问题,大多数情况下程序崩溃。

以下是将数据保存到磁盘的代码:

public static boolean saveFromRemoteSource(Context c, ArrayList<?> source){
    //Save context
    context = c;

    //Save source to local file
    File file = context.getFileStreamPath(PERSONS_FILE);

    //Status if successful in saving
    boolean savedStatus = false;

    try {
        if(!file.exists()){
            file.createNewFile();
        }else{
            //file already exists so don't do anything
        }
        //now load the data into the file

        FileOutputStream fos = context.openFileOutput(PERSONS_FILE, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(source);
        oos.close();
        savedStatus = true; 
    } catch(IOException e){
        e.printStackTrace();
        savedStatus = false; 
    }
    return savedStatus;
}

以下是从磁盘读取数据的代码:

    public static boolean loadPersonsArray(Context c){
    context = c;

    boolean loadStatus = false;

    File file = context.getFileStreamPath(PERSONS_FILE);

    try{
            if(!file.exists()){
                file.createNewFile();
            }else {
                //File is already created, do nothing
            }

            BufferedReader br = new BufferedReader(new FileReader(file));     
                if (br.readLine() != null) {
                    FileInputStream fis = context.openFileInput(PERSONS_FILE);
                    ObjectInputStream in = new ObjectInputStream(fis);  
                    personsArray = (ArrayList<Person>) in.readObject();
                    in.close();
                    fis.close();
                    loadStatus = true;
                }
            br.close();
        } catch(IOException e){
            e.printStackTrace();
            Log.d("TAG", "IOException PERSONS_FILE file: " + e);
            loadStatus = false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            Log.d("TAG", "ClassNotFoundException PERSONS_FILE file classnotfound: " + e);
        }

return loadStatus;
}

这是Person类:

    import java.io.Serializable;

     public class Person implements Serializable, Comparable<Person>{
 //Person class

private static final long serialVersionUID = 1L;

private String personID;
private String personName;
private boolean displayPerson;


//default constructor
public Person(){
    super();
}

public Person(String personID,
         String personName,
         boolean displayPerson){

    super();
    this.personID = personID;
    this.personName = personName;
    this.displayPerson = displayPerson; 
}

//Accessor Methods
public String getPersonID(){
    return personID;
}
public String getPersonName(){
    return personName;
}
public boolean getDisplayPerson(){
    return displayPerson;
}

//setter methods

public void setPersonID(String personID){
    this.personID = personID;
}
public void setPersonName(String personName){
    this.personName = personName;
}
public void setDisplayPerson(boolean displayPerson){
    this.displayPerson = displayPerson;
}

@Override
public String toString(){
    return this.getPersonName().replaceAll("[^A-Za-z0-9]", "") + this.getDisplayPerson();
}

public int compareTo(Person otherPerson) {

    if(!(otherPerson instanceof Person)){
        throw new ClassCastException("Not a valid Person object!");
    }

    Person tempPerson = (Person)otherPerson;

    if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) > 0){
        return 1;
        }else if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) < 0){
            return -1;
        }else{
            return 0;
        }
     }
}

数据来自何处以写入文件

    private void downloadPersons(){     
    HashMap<String, String> params = new HashMap<String, String>();

    Kumulos.call("selectAllPersons", params, new ResponseHandler() {

    @Override
    public void didCompleteWithResult(Object result) {
        ArrayList<Object> personsList = new ArrayList<Object>();

        for(Object o : (ArrayList<?>)result){
            Person person = new Person();                       
            person.setPersonID(replaceNandT((String) ((HashMap<?,?>) o).get("personID")));
            person.setLawName(replaceNandT((String) ((HashMap<?,?>) o).get("personName")));
            person.setDisplayLaw(stringToBool((String)((HashMap<?,?>) o).get("displayPerson")));

            if(person.getDisplayPerson()==true){
                personsList.add(person);
                }
            } 

            //Save personsList to a file
            if(PersonsLoader.saveFromRemoteSource(context, personsList)){
                updateVersionNumber();
                isFinished=true;
                Log.d("TAG", "PersonsLoader.saveFromRemoteSource(context, personsList) success");
                }
        }
    });
}

那么您认为这次电话会发生什么?

1 个答案:

答案 0 :(得分:0)

删除测试File.exists()和File.createNewFile()调用的块。

  • 打开输出文件将在必要时创建它。
  • 打开文件进行读取时,如果文件不存在,将抛出FileNotFoundException。创建文件以避免这种情况毫无意义:它只会导致其他问题。

也摆脱了BufferedReader和readLine()调用。它们没有用处。对象输出流中没有行。

相关问题