将多个对象读写到文件
来源:互联网 发布:机油加盟代理淘宝 编辑:程序博客网 时间:2024/06/01 10:03
方法:
1.对象实现序列化 即
implements Serializable
2,将对个对象先存在数组中,3,将整个数组作为一个对象存入文件中
4,将整个数组作为一个对象读出来
代码事例:来自:http://www.iteye.com/problems/66209
java数组序列化后存储到文件,读出来的数据和写入的不一样5
**************************************************
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);
}
}
0 0
- 将多个对象读写到文件
- 对象 文件的读写
- 读写对象文件
- C++文件读写对象
- JS 读写文件到本地
- 如何将对象读写到 XML 中
- Archive将多个对象归档到同一个文件
- 存储对象到文件
- C# 读写CSV文件到DataTable
- 读写xml文件信息到textbox控件
- 将字符串读写到文件中
- freemarker将文件读写到HTML中
- Qt 读写文件,并显示到tablewidget
- 使用SharedPreferences读写文件到内存
- python读写文件file写入到mysql
- Properties集合读写数据到文件
- OC中读写文件到本地
- DFM文件中读写 TReader对象
- MMORPG游戏服务器技术选型参考
- 用ImageSwitcher实现图片动态切换
- JAVA NIO 基础(一)
- Golang初级系列教程-接口
- Visual Studio 2013快捷键
- 将多个对象读写到文件
- ViewPager使用中的一些小问题
- 深入理解java异常处理机制
- javascript学习笔记(一)
- Origin字段
- 第八讲 泛化物品
- 站点新福音:百度搜索关键词影响力指数在H5版本站长平台上线
- leetcode Odd Even Linked List
- 关于python-dbus的问题