inblog logo
|
programmer
    Java

    Stream 통신

    [Java] 그림을 통해 스트림 통신 이해하고 예제 연습해보기
    Jan 08, 2024
    Stream 통신
    Contents
    스트림 통신 예제

    스트림 전송 그림

    notion image
    • (Byte) Stream : 끝이 없는 Byte의 흐름 (물길)
    • 버퍼 : 공급이 소비보다 많을 때 필요함
    • 파일은 한 번에 보조스트림(버퍼)의 크기 만큼 데이터를 소비한다.
    • 버퍼가 꽉 차야지만 파일이 데이터를 소비한다.
    • flush : 강제로 버퍼의 데이터를 파일로 흘려보내는 것(원래는 꽉 차야지만 데이터를 소비함)

    스트림 통신 예제

    InputStreamReader

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class StreamEx03 { public static void main(String[] args) { InputStreamReader ir = new InputStreamReader(System.in); // 통신을 할 때에는 System.in 말고 소켓 BufferedReader br = new BufferedReader(ir); try { String line = br.readLine(); System.out.println(line); } catch (IOException e) { throw new RuntimeException(e); } } }

    OutputStreamWriter

    import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class StreamEx04 { public static void main(String[] args) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); try { bw.write("안녕 "); // readLine으로 읽기때문에 \n까지 읽어라고 \n을 입력해줘야함 bw.write("반가워\n"); bw.flush(); // 반드시 flush } catch (IOException e) { throw new RuntimeException(e); } } }

    notion image
    Share article

    programmer

    RSS·Powered by Inblog