1 package streamDemo; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.DataInputStream; 6 import java.io.DataOutputStream; 7 import java.io.FileInputStream; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 import java.io.InputStream; 11 import java.io.OutputStream; 12 13 public class StreamDemo { 14 public static void main(String[] args) throws IOException { 15 /* 16 * 下面演示java中的数据如何写入磁盘中的A.txt文档中 17 */ 18 19 // 节点流FileOutputStream直接以A.txt作为数据源操作 OutputStream 20 OutputStream fileOutputStream = new FileOutputStream("A.txt"); 21 22 // 过滤流BufferedOutputStream进一步装饰节点流,提供缓冲写 23 OutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); 24 // 过滤流DataOutputStream进一步装饰过滤流,使其提供基本数据类型的写 25 DataOutputStream out = new DataOutputStream(bufferedOutputStream); 26 27 out.writeChars("I love China,I am Chinese.I hate Japan" + "I love China,I am Chinese.I hate Japan"); 28 29 out.flush(); 30 out.close(); 31 // 此处输入节点流,过滤流正好跟上边输出对应,读者可举一反三 32 InputStream fileInputputStream = new FileInputStream("A.txt"); 33 34 InputStream bufferedInputputStream = new BufferedInputStream(fileInputputStream); 35 36 DataInputStream in_0 = new DataInputStream(bufferedInputputStream); 37 38 in_0.close(); 39 40 /* 41 * 从磁盘的B.txt文档中读入数据到java程序中 42 */ 43 44 InputStream fileInputStream = new FileInputStream("B.txt"); 45 46 InputStream bufferedInputStream = new BufferedInputStream(fileInputStream); 47 48 DataInputStream in_1 = new DataInputStream(bufferedInputStream); 49 50 System.out.print(in_1.readLine()); 51 52 } 53 }