반응형

입출력에 관해서는 구현할 일이 없어서 한 번도 공부해 본적이 없는 부분인데 항상 궁금하긴 했었다.
문법 조차 몰랐던 부분이다.

이번에 HTTP 요청과 응답을 구현하기 위해 알아야 해서 가볍게 문법만 살펴 보았다.

InputStream


  • 1byte만 읽을 수 있다.
  • 아스키 코드로 반환된다.
  • 그래서 아주 불편하다.
  • 파일 전송 시 사용하기는 좋다.
public class Test {

    public static void main(String[] args) throws IOException {
        InputStream in = System.in;

        int a = in.read();
        System.out.println(a);
    }
}

// a -> 입력
// 97 -> 출력

여러 바이트를 읽기 위해서도 마찬가지로 불편하다.

public class Test {

    public static void main(String[] args) throws IOException {
        InputStream in = System.in;

        byte[] a = new byte[3];
        in.read(a);

        System.out.println(a[0]);
        System.out.println(a[1]);
        System.out.println(a[2]);
    }
}

// abc -> 입력
// 아래는 출력
97
98
99

InputStreamReader


  • 이제 byte에서 char로 벗어나서 아스키 코드를 볼 필요가 없다.
  • 출력도 나름 편해졌다.
  • 그래도 배열을 직접 선언 해주어야 해서 불편하다.
  • 공백 단위로 읽기 때문에 한 줄을 다 읽으려면 따로 처리르 해주어야 한다.
public class Test {

    public static void main(String[] args) throws IOException {
        InputStream in = System.in;
        InputStreamReader inr = new InputStreamReader(in);

        char[] a = new char[3];
        inr.read(a);

        System.out.println(a);
    }
}

// abc d -> 입력
// abc -> 출력

BufferedReader


  • 위 두 클래스의 단점을 모두 해결했다.
  • 버퍼에 담아 놓기 때문에 빠르다.
  • 개행 단위로 읽기 때문에 한 줄씩 읽을 수 있는 것. \r\n이나 \r을 행으로 인식한다. 그렇지 않다면 null을 반환한다.
    null이면 더 이상 읽을게 없는 것.
    공식 문서 내용

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

public class Test {

    public static void main(String[] args) throws IOException {
        InputStream in = System.in;
        InputStreamReader inr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(inr);

        System.out.println(br.readLine());
    }
}

// abc def -> 입력
// abc def -> 출력

파일 읽기


웹 요청이 오면 /index.htm과 같은 리소스를 찾아서 파일을 읽어서 정적 페이지를 제공해야 하는 일이었다.
DataOutputStream를 활용 했다.

rufrnr 응답을 해주려면 byte단위로 전송을 해야하는데 그러기 위해
wireteBytes(), write()를 사용했다.

  • writeBytes()
    • 파일이 아닌 HTTP/1.1 200 OK와 같은 응답 헤더를 만들 때 사용.
    • 내부적으로 byte로 형변환 하여 사용된다.
  • write()
    • 파일을 응답 바디에 생성할 때 사용
    • 파일 자체를 byte로 넘겨준다.
반응형

'웹 프레임워크 만들며 알게된 것들' 카테고리의 다른 글

멀티 쓰레드란  (0) 2022.01.18
소켓 통신이란  (0) 2022.01.18
복사했습니다!