package test.java.io; import java.io.*; public class CopyImg { public static void main(String[] args) { // TODO Auto-generated method stub //1源:非文本文件 InputStream-->FileInputStream //1.1 加入缓冲区 BufferedInputStream //2目的:非文本文件 OutputStream-->FileOutputStream //2.1 加入缓冲区 BufferedOutputStream FileInputStream fi = null; FileOutputStream fo = null; BufferedInputStream bufi = null; BufferedOutputStream bufo = null; try { fi = new FileInputStream("1.jpg"); fo = new FileOutputStream("2.jpg"); bufi = new BufferedInputStream(fi); bufo = new BufferedOutputStream(fo); int ch = 0; byte[] arr = new byte[1024]; //循环 while((ch=bufi.read(arr, 0, 1023))!=-1){ bufo.write(arr,0,ch); } } catch (IOException e) { System.out.println(e.toString()); }finally{ try { if(bufi!=null) bufi.close(); } catch (Exception e2) { System.out.println(e2.toString()); } try { if(bufo!=null) bufo.close(); } catch (Exception e3) { System.out.println(e3.toString()); } } } } |
package test.java.io; import java.io.*; import java.util.ArrayList; import test.java.entity.Student; public class ObjectStreamTest { public static void main(String[] args) throws IOException, ClassNotFoundException{ Student stu1 = new Student("zhanghaitao",20,"man"); Student stu2 = new Student("zhaoji",21,"man"); Student stu3 = new Student("zhangjiayu",23,"man"); Student stu4 = new Student("caizhanqi",22,"man"); File f = new File("student.obj"); // writeObject(stu1,f); // Student stu3 = null; System.out.println("----------> start <--------"); //读取文件内存在的对象 ArrayList<Object> arr= readObject(f); if(arr!=null) System.out.println("arr不是空的"); for(Object stu : arr){ if(stu!=null) System.out.println(stu); } //向文件内写入对象 // ArrayList<Object> arr = new ArrayList<Object>(); // arr.add(stu1); // arr.add(stu2); // arr.add(stu3); // arr.add(null); // arr.add(stu1); // writeObject(arr,f); System.out.println("-----------> End <--------"); } public static ArrayList<Object> readObject(File f) throws IOException, ClassNotFoundException{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)); ArrayList<Object> objs = new ArrayList<Object>(); Object obj = null; while((obj = ois.readObject())!=null){ objs.add(obj); } ois.close(); return objs; } public static void writeObject(ArrayList<Object> objs,File f) throws IOException{ if(!f.exists()) f.createNewFile(); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true)); for(Object obj : objs){ oos.writeObject(obj); } oos.close(); } } |
谢永烽 发表于 2015-5-29 13:34
感谢分析,这个复习起来挺轻松的,自己可以稍作修改成为自己的笔记加深印象。感谢 ...
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |