NIO 패키지 중 Channel 을 이용한 예제 입니다.

한번은 유용하게 이용해 먹었습니다.

import java.io.*;
import java.nio.*;
import java.nio.channels.*; //FileChannel클래스를 사용하기 위해 import한다.
class mefile {

    public static void main(String[] args) throws Exception {
   
        String s=”Hello! getJAVA..안녕!! 겟자바..”;
        // 버퍼에 문자열 s를 담기 위해 바이트 배열을 바꾼다.
        byte[] by=s.getBytes();
        // 버퍼 생성
        ByteBuffer buf=ByteBuffer.allocate(by.length);
        // 바이트배열을 버퍼에 넣는다.
        buf.put(by);
        // 버퍼의 위치(position)는 0으로 limit와 capacity값과 같게 설정한다.
        buf.clear();
       
        // FileOutputStream 객체를 생성
        FileOutputStream f_out=new FileOutputStream(“a2.txt”);
        // getChannel()를 호출해서 FileChannel객체를 얻는다.
        FileChannel out=f_out.getChannel();
        // 파일에 버퍼의 내용을 쓴다.
        out.write(buf);
        // 채널을 닫는다. 이때 스트림도 닫힌다.
        out.close();
       
        // FileInputStream 객체 생성
        FileInputStream f_in=new FileInputStream(“a2.txt”);
        // getChannel()를 호출해서 FileChannel객체를 얻는다.
        FileChannel in=f_in.getChannel();
       
        //바이트 버퍼 생성. 이때 버퍼의 크기는 현재 파일의 크기만큼 만든다.
        // 파일의 크기는 리턴하는 size()는 long형을 리턴하므로 int형으로 캐스팅한다.
        ByteBuffer buf2=ByteBuffer.allocate((int)in.size());
       
        // 파일을 내용을 읽어 버퍼에 담는다.
        in.read(buf2);
       
        // array()로 버퍼의 내용을 바이트 배열로 바꾼다.
        byte buffer[] = buf2.array();
        // 스트링으로 변환–> 한글이 깨지지 않도록 하기 위해 한다.
        String a=new String(buffer);
        //출력한다.
        System.out.println(a);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *