1 String source = "ABCDEF123456";
2 int mid = source.length() / 2;
3
4 ByteArrayInputStream bytesIS = new ByteArrayInputStream(source.getBytes());
5
6 // 1. 顺序读取流
7 int b = 0;
8 while( -1 != (b = bytesIS.read())){
9 System.out.print(Integer.toHexString(b) + " ");
10 }
11 System.out.println();
12
13 // 2. 读取完毕之后 调用 read 始终返回 -1
14 b = bytesIS.read();
15 System.out.println(b);
16
17 // 对流进行重置
18 int index = 0;
19 bytesIS.reset();
20 while( -1 != (b = bytesIS.read())){
21 if(index++ == mid && bytesIS.markSupported()){
22 bytesIS.reset();
23 }
24 System.out.print(Integer.toHexString(b) + " ");
25 }
26 System.out.println();
27
28 // 标记流
29 index = 0;
30 bytesIS.reset();
31 while( -1 != (b = bytesIS.read())){
32 if(index++ == mid && bytesIS.markSupported()){
33 // bytesIS.reset();
34 bytesIS.mark(0);
35 }
36 System.out.print(Integer.toHexString(b) + " ");
37 }
38 System.out.println();
39 bytesIS.reset();
40 while( -1 != (b = bytesIS.read())){
41 System.out.print(Integer.toHexString(b) + " ");
42 }
43 System.out.println();
44 bytesIS.reset();
45 while( -1 != (b = bytesIS.read())){
46 System.out.print(Integer.toHexString(b) + " ");
47 }
48 System.out.println();
49
50 // 1. 读取文件 使用 FileInputStream 只能
51 File file = new File("e:/test.txt");
52 System.out.println(file.length());
53 FileInputStream FileIS = new FileInputStream(file);
54 while( -1 != (b = FileIS.read())){
55 System.out.print("0x" + Integer.toHexString(b) + " ");
56 }
57 System.out.println();
58
59 // 可以使用seek方法来随机的读取文件,但是对于 RandomAccessFile,并不是流类,
60 String mode = "r";
61 RandomAccessFile randomFile = new RandomAccessFile(file, mode);
62 while( -1 != (b = randomFile.read())){
63 System.out.print("0x" + Integer.toHexString(b) + " ");
64 }
65 System.out.println();
66 System.out.println(randomFile.getFilePointer());
67 System.out.println(randomFile.length());
68 randomFile.seek(6);
69 while( -1 != (b = randomFile.read())){
70 System.out.print("0x" + Integer.toHexString(b) + " ");
71 }
72 System.out.println();
73 randomFile.seek(0);
74 while( -1 != (b = randomFile.read())){
75 System.out.print("0x" + Integer.toHexString(b) + " ");
76 }
77 System.out.println();
78
79 // java.lang包中有一个文本描述的工具类 但是其提供的功能也是顺序读取。
80 // java.util.Scanner
81 Scanner scanner = new Scanner(file);
82 System.out.println(scanner.next());
83 scanner = scanner.reset();
84
85 // java.io.PushbackInputStream 过滤流
86 // 这个流提供了 unread 方法, 回退到缓冲区,
87 bytesIS.reset();
88 PushbackInputStream pis = new PushbackInputStream(bytesIS);
89 pis.unread(0x30);
90 System.out.println(Integer.toHexString(pis.read()));
91 System.out.println(Integer.toHexString(pis.read()));
92
93 // 到目前为止,只有流类基本上只能按流的顺序来读写。
94 ByteArrayOutputStream bytesOutPut = new ByteArrayOutputStream();
95 bytesOutPut.write(source.getBytes());
96 System.out.println(bytesOutPut.toString());
97 bytesOutPut.write(0x30);
98 System.out.println(bytesOutPut.toString());
99