IT/Java

[Java] NIO 기본동작방식 및 개념?

상짱 2022. 10. 11. 11:23
반응형

- NIO ( New Input Output )

- NIO의 동작 방식은 버퍼를 만들어서 채널에 쓰는 방식으로 동작한다.

- java.io 에서는 InputStream / OutputStream을 얻어서 별도의 읽기/쓰기로 동작되지만,

- java.nio 에서는 Stream에서 채널을 얻거나 또는 채널을 생성하면, 양방향으로 가능하다.

 

- NIO File 샘플 소스

package sample;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileNioSample {

	public static void test( String contents ) {

		// 1. path 설정
		Path path = Paths.get( "nio_file_test.txt" );
		try {

			// 쓰기
			// 2. 채널을 생성한다.
			//FileChannel fc = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ);
			FileChannel fc = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

			// 3. 캐릭터셋을 얻고, 버퍼를 만든다.
			Charset cs = Charset.defaultCharset();
			ByteBuffer bb = cs.encode( contents );

			// 채널에 버퍼를 쓴다.
			int wCnt = fc.write(bb);
			System.out.println(wCnt + "/" + bb.toString());

			fc.close();


			// 읽기
			fc = FileChannel.open(path, StandardOpenOption.READ);

			bb = ByteBuffer.allocate(1024);
			int rCnt = fc.read(bb);
			bb.flip(); // 버퍼의 포지션을 0 으로 옮김.
			System.out.println(rCnt + "/" + bb.toString());

			CharBuffer cb = cs.decode(bb);
			System.out.println(cb);

			fc.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String...strings) {
		FileNioSample.test("hello world~~ \nnio test start!!!");
	}
}

 

- 결과

콘솔 결과

 

파일 생성

 

반응형