자바 PrintStream 클래스 중 write() 메소드는
조회수 1615회
1 답변
-
가장 많이 사용하는 스트림 객체가 PrintStream 클래스의 객체입니다.
System.out 이 PrintStream 의 객체이기 때문에 stdout(표준출력) 에 출력하는 경우는 무조건 해당 객체를 이용한다 할 수 있습니다.
PrintStream 클래스에는 출력을 위한 메소드가 print 류와 write 류 각각 2개의 형태로 정의되어 제공됩니다.
보통 print(ln) 류의 메소드는 문자(열)을 쓰기하는 용도이며 write 메소드의 용도는 바이너리 데이터를 쓰기 위해서 사용합니다.
-> System.out.println("aaaa") aaaa -> System.out.write(97) a -> byte[] b = "abcdef".getBytes() | Added variable b of type byte[] with initial value byte[6] { 97, 98, 99, 100, 101, 102 } -> System.out.write(b) abcdef
System.out 객체가 화면에 출력(stdout)하는 PrintStream 이므로 위의 결과는 화면에 바로 출력이 됩니다.
파일에 출력하는 경우의 예제
-> import java.io.* -> File file = new File("out.txt") | Added variable file of type File with initial value out.txt -> FileOutputStream fos = new FileOutputStream( FileOutputStream( -> FileOutputStream fos = new FileOutputStream(file) | Added variable fos of type FileOutputStream with initial value java.io.FileOutputStream@29ee9faa -> PrintStream out = new PrintStream(fos) | Added variable out of type PrintStream with initial value java.io.PrintStream@cc285f4 -> out.print('a') -> out.println("test") -> byte[] b = "abcdef".getBytes() -> out.write(b) -> out.close()
out.txt 파일의결과는 아래와 같습니다.
allinux@DESKTOP-6C4D789:~$ cat out.txt atest abcdef
- 위의 예제 코드는 ubuntu 18.04, jshell(jdk 10.0.1) 에서 수행한 결과 입니다.
댓글 입력