언어/JAVA
JAVA : 자바의 빠른 입출력
하이후에호
2020. 1. 23. 23:38
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class TestIO {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int t_size = st.countTokens();
for(int i=0;i<t_size;i++)
System.out.println(st.nextToken());
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
입력
buffer t est ! 야
출력
buffer
t
est
!
야
주로 이렇게 쓰는데 read함수는 int형 함수를 반환한다고 되어있다. 하지만 Scanner처럼 사용할수는 없다.
1
2
3
4
5
6
7
8
9
10
11
|
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[] arr = new int[5];
for(int i=0;i<5;i++) {
arr[i] = in.read();
}
for(int a : arr)
System.out.println(a);
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
입력
10 25 14 12 11
출력
49
48
32
50
53
위에 보시는것처럼 10을 불러서 저장하는게 아니라 1 0 ' ' 2 5 를 불러 온다.
하지만 '1'은 int형으로 변환하면 49이기때문에 이렇게 찍히는 것을 알수 있다.
공백은 32 이처럼 빠른 입력을 위해서는 readLine을 사용하고 StringTokenizer 를 사용해서 분류해야한다
BufferedWrite 사용
1
2
3
4
5
6
7
8
|
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write("ABCDSADFS\n");
bw.write("AWWW\n");
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
write를 사용해 buffer에 저장하다음 flush를 사용에 출력한다.
1
2
3
4
5
6
7
8
9
10
11
|
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write("ABCDSADFS\n");
bw.write("AWWW\n");
bw.write("AAA");
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
하지만 close를 사용하면 write를 사용할수가 없다.
두개를 합쳐서 JAVA에서 제일빠른 입출력
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
while(st.hasMoreTokens()) {
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
반응형