Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

The Office Lover

Java IO와 NIO 본문

Backend

Java IO와 NIO

Michael Gary Scott 2023. 7. 21. 14:59

Java IO와 NIO

 

IO (Input / Output)

자바의 IO는 Input과 Output을 처리하는 방법입니다. InputStream과 OutputStream 클래스 계열을 사용하여 데이터를 읽고 쓰는 작업을 수행합니다. 

 

IO는 스트림(stream) 개념을 기반으로 하며, 한 번에 하나의 데이터를 읽고 쓰는 방식입니다.

아래는 대표적인 IO클래스 입니다.

  • FileInputStream
  • FileOuputStream
  • BufferedReader
  • BufferedWriter

IO는 단순하고 직관적인 인터페이스를 제공하지만, 대량의 데이터를 처리할 때는 비효율적일 수 있습니다.

import java.io.*;

public class IOExample {
    public static void main(String[] args) {
        try {
            // 파일에서 데이터 읽기
            FileInputStream fileInputStream = new FileInputStream("input.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            bufferedReader.close();

            // 파일에 데이터 쓰기
            FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

            bufferedWriter.write("Hello, World!");
            bufferedWriter.newLine();
            bufferedWriter.write("This is an example of IO.");

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

위의 예시에서 'input.txt' 파일에서 데이터를 읽어와서 출력하고, 'output.txt' 파일에 데이터를 씁니다. FileInputStream과 FileOutputStream은 파일에서 바이트 단위로 데이터를 읽고 쓰는 데 사용되며, InputStreamReader와 OutputStreamWriter는 문자 단위로 데이터를 읽고 쓰는데 사용됩니다. BufferedReader와 BufferedWriter는 버퍼를 사용하여 효율적인 입출력을 지원합니다.

 

 

 

 

NIO (Non-blocking IO)

NIO는 자바 1.4부터 도입된 비동기적인 입출력 방식입니다. NOI는 IO보다 더욱 유연하고 빠른 입출력 처리를 제공합니다. NIO는 채널(channel)과 버퍼(buffer)라는 개념을 중심으로 동작합니다. 

 

버퍼는 데이터를 저장하는 공간으로 사용되고, 채널은 데이터를 읽고 쓰는 역할을 수행합니다.

 

NIO는 Selector 클래스를 사용하여 하나의 스레드로 여러 채널을 모니터링하고, 데이터를 읽거나 쓸 준비가 된 채널만 처리할 수 있습니다. 이는 비동기적인 입출력 처리를 가능하게 합니다. 아래는 대표적인 NIO클래스입니다.

  • ByteBuffer
  • Selector
  • Channel

NIO는 대량의 데이터 처리 및 네트워크 프로그래밍에 특히 유용합니다.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class NIOExample {
    public static void main(String[] args) {
        try {
            // 파일에서 데이터 읽기
            Path path = Paths.get("input.txt");
            FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int bytesRead = fileChannel.read(buffer);
            while (bytesRead != -1) {
                buffer.flip(); // 버퍼를 읽기 위해 준비

                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get()); // 데이터 출력
                }

                buffer.clear(); // 버퍼 비우기
                bytesRead = fileChannel.read(buffer);
            }

            fileChannel.close();

            // 파일에 데이터 쓰기
            Path outputPath = Paths.get("output.txt");
            FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

            String data = "Hello, World! This is an example of NIO.";
            byte[] byteArray = data.getBytes();
            ByteBuffer outputBuffer = ByteBuffer.wrap(byteArray);

            outputChannel.write(outputBuffer);

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

위의 예시에서 'input.txt' 파일에서 데이터를 읽어와서 출력하고, 'output.txt' 파일에 데이터를 씁니다. FileChannel은 NIO에서 파일을 읽고 쓰는 데 사용되며, ByteBuffer는 데이터를 저장하고 처리하는 버퍼 역할을 합니다. FIilChannel의 'read()' 메서드를 사용하여 데이터를 읽고, 'write()' 메서드를 사용하여 데이터를 씁니다. NIO에서는 버퍼를 사용하여 데이터를 효율적으로 처리할 수 있습니다. 

 

 

2023.07.21 - [Backend] - Java blocking과 non-blocking

 

Java blocking과 non-blocking

Blocking I/O (블로킹 입출력) Blocking I/O는 입출력 작업 중에 해당 작업이 완료될 때까지 스레드가 블로킹되는 방식입니다. 즉, 입출력 작업이 완료되기 전까지 해당 스레드는 다른 작업을 수행할 수

daniel6364.tistory.com