java物件序列化與複製圖片
阿新 • • 發佈:2018-11-30
下面程式碼包括賦值多個圖片,物件的序列化,目的是將物件狀態存入檔案,再把物件狀態從檔案中讀取。
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();
}