자바 PrintStream 클래스 중 write() 메소드는

조회수 1615회

자바 PrintStream 클래스에서 write()메소드는 어떤 경우에 쓰이나요? 오라클 설명을 보는데 잘 감이 안와서 예제가 있으면 한번만 보고 싶습니다.

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) 에서 수행한 결과 입니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)