流---是指的一组有序的、有气垫和重点的字节集合,是对的护具传输的总称或者抽象。
流采用缓冲区技术,当写一个数据时,系统将数据发送到缓冲区而不是外部设备(如硬盘),当读一个数据时,系统实际是从缓冲区读取数据的。
流的存在:我们都知道输入流和输出流,二者的定义都是基于数据流向且是以内存为坐标的。标准输入过程中,数据从键盘等输入设备流向内存,这事输入流。标准输出过程中,数据从内存输出到显示器或者打印机等设备,这是输出流。
流分为字节流和字符流
下边主要讲标准输入输出、文件字节流、数据字节流和对象字节流四种字节流。
1 public class IOtest { 2 3 public static void main(String[] args) throws IOException { 4 5 // KeyboardInput(); 6 7 // byte[] buffer = {0,1,2,3,4,5,6,7,8,9}; 8 // ByteFile afile = new ByteFile("info.txt"); 9 // afile.writeToFile(buffer); 10 // afile.readFromFile(); 11 // afile.copyFile("io2.txt"); 12 13 // IntFile afile = new IntFile("fileInt.txt"); 14 // afile.writeToFile(); 15 // afile.readFromFile(); 16 17 Student stus[] = { new Student("张三", "男"), new Student("李四", "女"), new Student("王五", "女博士")}; 18 objectFile afile = new objectFile("students.dat"); 19 afile.writeToFile(stus); 20 System.out.println("stus: \n" + afile.readFromFile()); 21 } 22 23 //标准输入输出 24 public static void KeyboardInput() throws IOException{ 25 System.out.print("Input:"); 26 byte buffer[] = new byte[512]; //以字节数组作为缓冲区 27 int count = System.in.read(buffer); 28 System.out.print("Output:"); 29 for(int i=0; i0); 99 dout.close();100 fout.close();101 }102 public void readFromFile() throws IOException{103 FileInputStream fin = new FileInputStream(this.filename);104 DataInputStream din = new DataInputStream(fin);105 System.out.println(this.filename + ": ");106 while(true){107 try {108 int i = din.readInt();109 System.out.print(i + " ");110 } catch (Exception e) {111 break;112 }113 }114 din.close();115 fin.close();116 }117 }118 119 //对象字节流120 //使用对象字节流读写多个学生对象到某个指定文件121 static class objectFile{122 String filename;123 public objectFile(String filename){124 this.filename = filename;125 }126 127 public void writeToFile(Object[] objs) throws IOException{128 FileOutputStream fout = new FileOutputStream(this.filename);129 ObjectOutputStream obout = new ObjectOutputStream(fout);130 for(int i = 0; i