- InputStream OutputStream vs Reader Writer
- An OutputStream is a byte-oriented stream. Any text you write has to be encoded as bytes using some encoding (most commonly ISO-8859-1 or UTF-8). A Writer is a character-oriented stream that may or may not internally encode characters as bytes, depending on what it is writing to.
- Stream, Buffer in Java
- Java streams enable functional-style operations on streams of elements. A stream is an abstraction of a non-mutable collection of functions applied in some order to the data. A stream is not a collection where you can store elements.
- 컴퓨터 공학 전반에서 이야기되는 스트림(Stream)은 데이터가 출발지에서 도착지로 단일 방향으로 흘러가는 개념을 의미한다. 데이터는 키보드에서 프로그램으로, 프로그램에서 모니터로, 프로그램에서 파일로 혹은 소켓과 소켓으로 흐를 수 있다.
-프로세스가 데이터의 도착지라면 입력 스트림(InputStream), 프로세스가 데이터의 출발지라면 출력 스트림(OutputStream) 이라고 불린다. 기준은 항상 프로그램이다.
- A Buffer is a portion in the memory that is used to store a stream of data from peripheral devices. Then from this buffer this stream of data is collected and stored in variables. A stream can be defined as a continuous flow of data.
-The very term “input/output” means nothing more than moving data in and out of buffers. Just keep this in your mind all the time. Processes perform I/O by requesting of the operating system that data to be drained from a buffer (write operation) or that a buffer be filled with data (read operation).
- BufferedReader, BufferedWriter
- NB: The BufferedWriter does not write to the output stream directly, it actually writes into a buffer(whose essential properties are capacity, position, and limit), which is then written into stream for efficiency. Also, you can set the size of that buffer in the constructor or leave it as default if you want. So when the close() method is evoked, the buffer not written is written into the stream.
- Also if the idea of closing the stream does not appeal to you, you can opt to flush the buffer into the file, by using the flush() method.
- Scanner vs BufferedReader
- 그리고 버퍼 사이즈도 Scanner가 1024 char인데 비해, BufferedReader는 8192 char(16,384byte) 이기 때문에 입력이 많을 때 BufferedReader가 유리하다.
- 또한 BufferedReader는 동기화 되기 때문에 멀티 쓰레드 환경에서 안전하고, Scanner는 동기화가 되지 않기 때문에 멀티 쓰레드 환경에서 안전하지 않다. (멀티 쓰레드에 대한 설명은 생략한다.)
- Scanner는 띄어쓰기와 개행문자를 경계로 하여 입력 값을 인식한다. 그렇기 때문에 따로 가공할 필요가 없어 편리하다.
- Scanner와 달리 BufferedReader는 개행문자만 경계로 인식하고 입력받은 데이터가 String으로 고정된다. 그렇기 때문에 따로 데이터를 가공해야하는 경우가 많다. 하지만 Scanner보다 속도가 빠르다!
// StringTokenizer
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
// String.split() 함수
String arr[] = s.split(" ");
- 특별한 case 가 아니면 무조건 buffer를 사용한다.
- StringBuilder
- StringBuffer : 동기화를 지원하여 멀티 쓰레드 환경에서 안전하다.
- StringBuilder : 동기화를 지원하지 않아 멀티 쓰레드 환경에 사용하기 적합하지 않다. 대신, 동기화를 지원하지 않기에 단일쓰레드에서는 StringBuffer보다 성능이 뛰어나다.
- String은 불변성을 가지기 때문에 변하지 않는 문자열을 자주 읽어들이는 경우 사용하면 유리하다. 하지만 문자열 추가, 삭제, 수정 등의 연산이 자주 일어나는 경우에 String을 사용하면, 힙 메모리에 많은 Garbage가 생성되고, 이는 힙 메모리 부족으로 이어져 프로그램의 성능에 치명적 영향을 미칠 수 있다.
- IO / NIO
- 자바 4부터 새로운 입출력(New Input/Output)이라는 뜻에서 java.nio 패키지가 포함되었는데 자바 7로 버전업하면서
IO와 NIO 사이의 일관성 없는 클래스 설계를 바로 잡고 비동기 채널 등의 네트워크 지원을 대폭 강화한 NIO.2 API가 추가되었다. NIO.2는 java.nio2 패키지로 제공되지 않고 기존 java.nio의 하위 패키지(java.nio.channels, java.nio.charset, java.nio.file)에 통합되어 있다.
- IO는 스트림, 넌버퍼, 동기 블로킹 NIO는 채널, 버퍼, 동기비동기 블로킹논블로킹 모두 지원. 스트림은 단방향인데 채널은 양방향으로 입출력이 가능함.
- 파일 생성, 쓰기, 읽기, 속성정보 확인, 디렉토리 복사, 이동, 삭제, 생성 등은 Path, Files 잘 활용하면 됨.
- 채널과 바이트버퍼 (양방향 통신 가능한 channel을 RandomAccessFile 로부터 생성하고 버퍼 등록)
- Selector (Multiplexing - 하나의 스레드에서 polling 방식으로 입출력 기다렸다 해결. 원래는 한 스레드 당 하나의 채널)
https://hbase.tistory.com/36
- 파일트리
- 랜덤 엑세스 파일
대부분의 입출력 스트림들은 파일에 순차적으로 입출력 작업을 수행한다.
RandomAccessFile class는 입출력 클래스 중 유일하게 파일에 대한 입력과 출력을 동시에 할 수 있는 클래스이다.
RandomAccessFile 클래스는 파일만을 대상으로한다.
파일 포인터가 있어서 읽고 쓰는 위치의 이동이 가능하다. (seek 메소드를 활용)
순차적인 접근이 아닌 임의의 지접에 접근하여 작업을 수행하고 싶다면 사용하기 좋다.
RandomAccessFile 클래스의 생성자에는 인수로 파일의 이름뿐만 아니라 파일 모드까지 함께 전달해야한다.
- 파일 모드 종류
- 디렉터리 변경 감지