下面代码包括赋值多个图片,对象的序列化,目的是将对象状态存入文件,再把对象状态从文件中读取。
DataInputStream dis;
DataOutputStream dos;
FileInputStream fi = null;
FileOutputStream fo = null;
try {
/*
dis=new DataInputStream(new FileInputStream("D:\\java\\zs2\\feifei.png"));
dos=new DataOutputStream(new FileOutputStream("D:\\java\\zs2\\fafa.png"));
*/
int copytime=100;
while(copytime-->0){ //while循环批量复制
fi=null;
fo=null;
Thread.sleep(300);
fi=new FileInputStream("D:\\java\\zs2.jpg");
fo=new FileOutputStream("D:\\java\\zs2"+copytime+".jpg");//拼接成一百个不同的命名
int n=0;
while((n=fi.read())!=-1){ //单个文件里,用n存read()值,n传给write(),read()write()只能一一对应。
fo.write(n);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
fi.close();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
ObjectOutputStream oos=null; //序列化
fo=null;
try {
fo=new FileOutputStream("D:\\java\\zs2\\eatshit.dll");
oos=new ObjectOutputStream(fo);
man m=new Main().new man(5,"shit",'M');//相关的类以及外部类都要实现Serializable接口
oos.writeObject(m);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
fi=null;
ObjectInputStream ois=null; //反序列化
try {
fi=new FileInputStream("D:\\java\\zs2\\eatshit.dll");
ois=new ObjectInputStream(fi);
man m=(man)ois.readObject();
System.out.println(m.age+" "+m.name+" "+m.sex);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}