-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadExample.java
More file actions
42 lines (40 loc) ยท 1.46 KB
/
ReadExample.java
File metadata and controls
42 lines (40 loc) ยท 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package ch18.sec04.exam02;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class ReadExample {
public static void main(String[] args) {
try {
Reader reader = null;
// ํ
์คํธ ํ์ผ๋ก๋ถํฐ ๋ฌธ์ ์
๋ ฅ ์คํธ๋ฆผ
reader = new FileReader("temp/test.txt");
while (true) {
// 1 ๋ฌธ์๋ฅผ ์ฝ์
int data = reader.read();
// ํ์ผ์ ๋ค ์ฝ์ผ๋ฉด while ๋ฌธ ์ข
๋ฃ
if (data == -1) break;
// ์ฝ์ ๋ฌธ์ ์ถ๋ ฅ
System.out.print((char) data);
}
reader.close();
System.out.println();
// ํ
์คํธ ํ์ผ๋ก๋ถํฐ ๋ฌธ์ ์
๋ ฅ ์คํธ๋ฆผ
reader = new FileReader("temp/test.txt");
// ์ฝ์ ๋ฌธ์๋ฅผ ์ ์ฅํ ๋ฐฐ์ด ์์ฑ
char[] data2 = new char[100];
while (true) {
// ์ฝ์ ๋ฌธ์๋ ๋ฐฐ์ด์ ์ ์ฅ, ์ฝ์ ๋ฌธ์ ์๋ ๋ฆฌํด
int num = reader.read(data2);
// ํ์ผ์ ๋ค ์ฝ์ผ๋ฉด while ๋ฌธ ์ข
๋ฃ
if (num == -1) break;
for (int i = 0; i < num; i++) { // ์ฝ์ ๋ฌธ์ ์๋งํผ ์ถ๋ ฅ
System.out.print(data2[i]);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}