--文件的复制and剪切
File file = new File("f:\\图片\\0809.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bs = new byte[(int)file.length()];
bis.read(bs);
bis.close();
fis.close();
File newF = new File("f:\\0105.txt");
FileOutputStream fos = new FileOutputStream(newF);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bs);
bos.close();
fos.close();
file.delete();
System.out.println("ok");
之前我们操作的只能是字符串 今天我们要学读写的高级类
--序列化and反序列化
在实际工作中,可以把数据从硬盘的介质中导入 还可以从内存中导出去
//序列化:把一个对象从内存中存放到硬盘中的过程
//所有要序列化的类都必须实现Serializable接口
Dog d=new Dog("来福1","公",23);
File file = new File("f:\\图片\\dog1");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(d);
//关闭必须由内而外!
oos.close();
bos.close();
fos.close();
System.out.println("ok");
//反序列化:将对象从硬盘介质中还原到内存中
File file = new File("f:\\图片\\dog");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Dog d = (Dog)ois.readObject();
System.out.println(d.getName());
ois.close();
bis.close();
fis.close();
保存1000只狗
ArrayList<Dog> dogs = new ArrayList<Dog>();
for (int i = 0; i < 1000; i++) {
Dog d = new Dog("旺财"+i, "公", i+1);
dogs.add(d);
}
File file = new File("f:\\图片\\dogs.bak");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(dogs);
oos.close();
bos.close();
fos.close();
System.out.println("完美?");
是不是所有实现序列化的类都必须实现Serializable接口?那么arrayList集合捏?Dog还有没有必要?