java.lang.ioパッケージの使用
12162 ワード
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