xyh9717
xyh9717
2011-05-31 21:47

java数组序列化后存储到文件,读出来的数据和写入的不一样

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

import java.io.Serializable;
public class Map implements Serializable{
private byte[][] map;

public byte[][] getMap() {
    return map;
}
public void setMap(byte[][] map) {
    this.map = map;
}

}


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Vector;

public class ControlMap {

Vector<Map> mapVector=new Vector<Map>();

public void writeMap(byte myMap[][])
{
    readMap();
    ObjectOutputStream oos;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("map.map"));
        Map map=new Map();
        map.setMap(myMap);
        mapVector.add(map);
        oos.writeObject(mapVector);
        oos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public void readMap()
{
    try {
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("map.map"));
        mapVector=(Vector)(ois.readObject());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


public String toString()
{
    readMap();
    int size=mapVector.size();
    String temp="";
    for(int i=0;i<size;i++)
    {
        temp+="第"+(i+1)+"张地图:\n";
        Map map=mapVector.get(i);
        byte mapData[][]=map.getMap();
        for(int j=0;j<mapData.length;j++)
            temp+=Arrays.toString(mapData[i])+"\n";
        temp+="\n";
    }
    return temp;
}

}


public class Test {

public static void main(String[] args) {
    ControlMap control=new ControlMap();
    byte [][] myMap={
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8},
            {3,7,5,2,4,6,8}
    };
    control.writeMap(myMap);
    System.out.println(control);
}

}


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐