📄 iodemo.out
字号:
1: //: c11:IOStreamDemo.java
2: // Typical I/O stream configurations.
3:
4: import java.io.*;
5:
6:
7: public class IOStreamDemo {
8:
9: // Throw exceptions to console:
10:
11: public static void main(String[] args)
12: throws IOException {
13: // 1. Reading input by lines:
14:
15:
16: BufferedReader in =new BufferedReader(new FileReader("IOStreamDemo.java"));
17: String s, s2 = new String();
18: while((s = in.readLine())!= null)
19: s2 += s + "\n";
20: in.close();
21:
22:
23: // 1b. Reading standard input:
24: BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));
25: System.out.print("Enter a line:");
26: System.out.println(stdin.readLine());
27:
28:
29: // 2. Input from memory
30: StringReader in2 = new StringReader(s2);
31: int c;
32: while((c = in2.read()) != -1)
33: System.out.print((char)c);
34:
35:
36: // 3. Formatted memory input
37: try
38: {
39: DataInputStream in3 =new DataInputStream(new ByteArrayInputStream(s2.getBytes()));
40: while(true)
41: System.out.print((char)in3.readByte());
42:
43: } catch(EOFException e)
44:
45: {
46: System.err.println("End of stream");
47: }
48:
49:
50: // 4. File output
51: try {
52: BufferedReader in4 =new BufferedReader(new StringReader(s2));
53: PrintWriter out1 =new PrintWriter(new BufferedWriter(new FileWriter("IODemo.out")));
54: int lineCount = 1;
55: while((s = in4.readLine()) != null )
56: out1.println(lineCount++ + ": " + s);
57: out1.close();
58: } catch(EOFException e)
59: { System.err.println("End of stream");
60: }
61:
62:
63: // 5. Storing & recovering data
64: try {
65: DataOutputStream out2 =new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
66: out2.writeDouble(3.14159);
67: out2.writeChars("That was pi\n");
68: out2.writeBytes("That was pi\n");
69: out2.close();
70: DataInputStream in5 =new DataInputStream(new BufferedInputStream(new FileInputStream("Data.txt")));
71: BufferedReader in5br =new BufferedReader(new InputStreamReader(in5));
72:
73: // Must use DataInputStream for data: System.out.println(in5.readDouble());
74:
75:
76: // Can now use the "proper" readLine():
77: System.out.println(in5br.readLine());
78: // But the line comes out funny.
79: // The one created with writeBytes is OK: System.out.println(in5br.readLine());
80: } catch(EOFException e) { System.err.println("End of stream");
81: }
82:
83:
84: // 6. Reading/writing random access files
85:
86: RandomAccessFile rf=new RandomAccessFile("rtest.dat", "rw");
87: for(int i = 0; i < 10; i++) rf.writeDouble(i*1.414);
88: rf.close();
89:
90:
91: rf =
92: new RandomAccessFile("rtest.dat", "rw");
93: rf.seek(5*8); rf.writeDouble(47.0001); rf.close();
94:
95:
96: rf =new RandomAccessFile("rtest.dat", "r");
97: for(int i = 0; i < 10; i++)
98: System.out.println("Value " + i + ": " +rf.readDouble());
99:
100: rf.close();
101:
102: }
103: }
104:
105:
106:
107:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -