错误“java.io.StreamCorruptedException:无效的流标题:5B424037”

时间:2014-11-01 20:19:38

标签: java java-io

我有一个实现FootballPlayer接口的Serializable实体类。我使用longblob类型将对象从此类保存到数据库表。

这样做很好,但是从数据库中检索对象时,我得到的是StreamCorruptedException

这是我的代码:

public FootballPlayer searchFBPlayer(String id){

        try {

            String sql = "SELECT * FROM player";
            ResultSet rs = DBConnection.getData(sql);
            // search for player
            while (rs.next()) {
                ByteArrayInputStream bais = new ByteArrayInputStream(rs.getBytes("fbPlayer"));
                //test
                if(bais==null) System.out.println("Null BAIS");
                else System.out.println("No Null BAIS");
                //test
                FootballPlayer fbp = (FootballPlayer) toObject(bais);
                if(fbp.getPlayerID().equals(id))
                    return fbp;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


private Object toObject(ByteArrayInputStream arr){

        ObjectInputStream ins;
        try{
        ins = new ObjectInputStream(arr);
        return ins.readObject();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

保存代码:

public int addFootballPlayer(FootballPlayer player){

        byte[] data=toByte(player);
        String sql="INSERT INTO footballplayer(footballPlayer) VALUES('"+data+"')";
        return DBConnection.setData(sql);
    }

private byte[] toByte(Object obj){

        try{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        bos.close();

        byte[] data = bos.toByteArray();
        return data;

        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

这是我的堆栈跟踪:

java.io.StreamCorruptedException: invalid stream header: 5B424037
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at com.league.database.DBAccess.toObject(DBAccess.java:67)
    at com.league.database.DBAccess.searchPlayer(DBAccess.java:34)
    at com.league.main.Test.main(Test.java:20)

我的代码中没有任何类型的网络,例如套接字。我做错了什么,我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

问题是您创建SQL的关键。此时您应该使用PreparedStatement,并将数据作为参数传递:不将数据转换为String。