Java NIO-파일 채널

기술

이미 언급했듯이 Java NIO 채널의 FileChannel 구현은 생성, 수정, 크기 등을 포함한 파일의 메타 데이터 속성에 액세스하기 위해 도입되었습니다.이 파일 채널과 함께 다중 스레드가있어 Java NIO가 Java IO보다 더 효율적입니다.

일반적으로 FileChannel은 파일에 연결된 채널로 파일에서 데이터를 읽고 파일에 데이터를 쓸 수 있으며, FileChannel의 또 다른 중요한 특징은 논 블로킹 모드로 설정할 수 없다는 것입니다. 항상 차단 모드로 실행됩니다.

파일 채널 객체를 직접 얻을 수 없습니다. 파일 채널의 객체는

  • getChannel() − FileInputStream, FileOutputStream 또는 RandomAccessFile의 메소드.

  • open() − 기본적으로 채널을 여는 파일 채널 방법.

File 채널의 객체 유형은 객체 생성에서 호출되는 클래스 유형에 따라 다릅니다. 즉, FileInputStream의 getchannel 메소드를 호출하여 객체가 생성되면 파일 채널이 읽기 위해 열리고 쓰기 시도시 NonWritableChannelException이 발생합니다.

다음 예제는 Java NIO FileChannel에서 데이터를 읽고 쓰는 방법을 보여줍니다.

다음 예제는 텍스트 파일에서 읽습니다. C:/Test/temp.txt 콘텐츠를 콘솔에 인쇄합니다.

temp.txt

Hello World!

FileChannelDemo.java

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
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;
import java.util.HashSet;
import java.util.Set;

public class FileChannelDemo {
   public static void main(String args[]) throws IOException {
      //append the content to existing file 
      writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes()));
      //read the file
      readFileChannel();
   }
   public static void readFileChannel() throws IOException {
      RandomAccessFile randomAccessFile = new RandomAccessFile("C:/Test/temp.txt",
      "rw");
      FileChannel fileChannel = randomAccessFile.getChannel();
      ByteBuffer byteBuffer = ByteBuffer.allocate(512);
      Charset charset = Charset.forName("US-ASCII");
      while (fileChannel.read(byteBuffer) > 0) {
         byteBuffer.rewind();
         System.out.print(charset.decode(byteBuffer));
         byteBuffer.flip();
      }
      fileChannel.close();
      randomAccessFile.close();
   }
   public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException {
      Set<StandardOpenOption> options = new HashSet<>();
      options.add(StandardOpenOption.CREATE);
      options.add(StandardOpenOption.APPEND);
      Path path = Paths.get("C:/Test/temp.txt");
      FileChannel fileChannel = FileChannel.open(path, options);
      fileChannel.write(byteBuffer);
      fileChannel.close();
   }
}

산출

Hello World! Welcome to TutorialsPoint