ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [NIO.2]SeekableByteChannel
    JAVA/NIO2 2014. 2. 4. 17:23

    SeekableByteChannel 인터페이스는 채널에서 위치라는 개념을 구현하여 RAF를 지원 합니다.


    채널에서 바이트 버퍼를 읽어올 수 있고, 바이트 버퍼를 채널에 쓸 수 있으며, 현재 위치 지정과 설정, 지원된 차원의 채널에 연결된 엔티티를 잘라내기를 할 수 있습니다.


    다음은 이러한 기능을 지원 하는 메소드 입니다.

    • postion() : 채널의 현재 위치를 반환한다.(정수)
    • position(long) : 채널의 위치를 long 값으로 지정한다.(정수)
    • truncate(long) : long 값의 채널에 연결된 엔티티를 잘라낸다.
    • read(ByteBuffer) : 바이트를 채널에서 버퍼로 읽어 들인다.
    • write(ByteBuffer) : 바이트를 채널에서 버퍼로 쓴다.
    • size() : 이 채널의 연결된 엔티티의 현재 크기를 반환한다.


    사용 예제 1 파일 읽기

     public void fileRead(){
            Path path = Paths.get("C:/TEMP", "story.txt");
            String encoding = System.getProperty("file.encoding");
            try(SeekableByteChannel seekableByteChannel = Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ))){
                ByteBuffer buffer = ByteBuffer.allocate(12);
                buffer.clear();
    
                while(seekableByteChannel.read(buffer) > 0){
                    buffer.flip();
                    System.out.print(Charset.forName(encoding).decode(buffer));
                    buffer.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    사용예제 2 파일 쓰기

    public void fileWrite(){ Path path = Paths.get("C:/TEMP", "story.txt"); String encoding = System.getProperty("file.encoding"); try(SeekableByteChannel seekableByteChannel = Files.newByteChannel(path, EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.APPEND))){ ByteBuffer buffer = ByteBuffer.wrap("Write TEST".getBytes()); int write = seekableByteChannel.write(buffer); System.out.println("Number of written bytes : "+write); buffer.clear(); } catch (IOException e) { e.printStackTrace(); } }


    파일을 쓸때에는 열기 옵션과 조합해서 쓰는 몇가지 공통된 예가 있다.

    - 파일이 있고 시작 부분에 쓰려면 WRITE를 사용해야 한다.

    - 파일이 있고 끝 부분에 쓰려면 WRITE와 APPEND를 사용한다.

    - 파일이 있고 파일의 내용을 정리한다.다음에 쓰려면 WRITE와 TRUNCATE_EXISTING을 사용한다.

    - 파일이 없는데 쓰려면 CREATE 또는 CREATE_NEW 와 WRITE를 사용한다.


    사용예제 3 위치 이동해서 읽기 사용하기

     public void readPosition(){
            Path path = Paths.get("C:/TEMP", "story.txt");
            String encoding = System.getProperty("file.encoding");
            ByteBuffer buffer = ByteBuffer.allocate(1);
            try(SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ)))){
                //Init value
                seekableByteChannel.position(0);
    
                System.out.println("Reading one character form postion : "+ seekableByteChannel.position());
                seekableByteChannel.read(buffer);
                buffer.flip();
                System.out.print(Charset.forName(encoding).decode(buffer));
                buffer.rewind();
                //half
                seekableByteChannel.position(seekableByteChannel.size()/2);
    
                System.out.println("\nReading one character from position :" + seekableByteChannel.position());
                seekableByteChannel.read(buffer);
                buffer.flip();
                System.out.print(Charset.forName(encoding).decode(buffer));
                buffer.rewind();
    
                //last
                seekableByteChannel.position(seekableByteChannel.size()-1);
    
                System.out.println("\nReading one character from position :" + seekableByteChannel.position());
                seekableByteChannel.read(buffer);
                buffer.flip();
                System.out.print(Charset.forName(encoding).decode(buffer));
                buffer.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    사용예제 4 위치 이동해서 쓰기 사용하기

      Path path = Paths.get("C:/TEMP", "story.txt");
            String encoding = System.getProperty("file.encoding");
            ByteBuffer buffer_1 = ByteBuffer.wrap("GREAT playrs participate in our tournament, like: Tommy robredo, Fernando Gonzalez, jose Acasuso or Thomaz Bellucci.".getBytes());
            ByteBuffer buffer_2 = ByteBuffer.wrap("Gonzalez".getBytes());
    
            try(SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.WRITE)))){
                //파일 끝으로 이동
                seekableByteChannel.position(seekableByteChannel.size());
    
                while (buffer_1.hasRemaining()){
                    seekableByteChannel.write(buffer_1);
                }
    
                //Gonsales를 Gonzalez로 바꾼다.
                seekableByteChannel.position(301);
    
                while (buffer_2.hasRemaining()){
                    seekableByteChannel.write(buffer_2);
                }
    
                buffer_1.clear();
                buffer_2.clear();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    


    사용예제 5 파일의 일부분 잘라내기 기능

     public void truncatePosition(){
            Path path = Paths.get("C:/TEMP", "story.txt");
            String encoding = System.getProperty("file.encoding");
            ByteBuffer buffer = ByteBuffer.wrap("GREAT playrs participate in our tournament, like: Tommy robredo, Fernando Gonzalez, jose Acasuso or Thomaz Bellucci.".getBytes());
    
            try(SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.WRITE)))){
                //파일 끝으로 이동
                seekableByteChannel.truncate(200);
    
                seekableByteChannel.position(seekableByteChannel.size()-1);
                while (buffer.hasRemaining()){
                    seekableByteChannel.write(buffer);
                }
                buffer.clear();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    



    참고자료 : http://openjdk.java.net/projects/nio/javadoc/java/nio/channels/SeekableByteChannel.html

    'JAVA > NIO2' 카테고리의 다른 글

    [NIO.2]FileChannel  (0) 2014.02.05
    [NIO.2]ByteBuffer  (0) 2014.02.04
    [NIO.2]File Store Attributes  (0) 2013.12.30
    [NIO.2]User-Defined File Attributes  (0) 2013.12.30
    [NIO.2] POSIX FIle Permissions  (0) 2013.12.16
Designed by Tistory.