'java nio'에 해당되는 글 1건

  1. 2015.01.16 nio (jdk1.4)

nio (jdk1.4)

java core 2015. 1. 16. 15:23

레퍼런스:  http://javacan.tistory.com/tag/nio



속도가 향상된 nio(new io)는 기존 java라기 보단 c코드라고 봐야할 것 같다.


DirectBuffer가 속도가 빠르고, IndirectBuffer는 임시용.

Buffer는 보통 Channel(c언어로 된 Stream이라고 보면 될듯) 과 함께 써야 함.



  ByteBuffer buf = ByteBuffer.allocateDirect(8); 

    buf.putByte( (byte)0xAB );

    buf.putShort( (short)0xCDEF ); 


이렇게 하면, buf에 position=3,  limit=8=capacity 이 됨.

buf.rewind : p=0.

buf.clear() :  p=0, l=8 (초기상태)

buf.flip()    :  p=0, limit=3(현재위치)


뭔가 write한 후에는 남은 byte를 맨 앞으로 옮겨주는

buf.compact() 필요.  주로 buf.isRemaining()과 함께 쓰이는 듯.



<<실제 예제>> 

    FileChannel inputChannel = null;

    FileChannel outputChannel = null;

    try {

        FileIntputStream is = new FileInputStream(source);

        FileOutputStream out = new FileOutputStream(dest);

        inputChannel = is.getChannel();

        outputChannel = out.getChannel();        


    } catch(IOException ex) {



    ByteBuffer buffer = ByteBuffer.allocateDirect(512);

    int len ;

    while ( (len = inputChannel.read(buffer)) != -1) {

         buffer.flip(); //뒤쪽 limit을 마킹. 즉 limit=position,  position=0이 됨


        outputChannel.write(buffer); //읽은거 그대로 write.

        buffer.clear(); //p=0, limit=512가 됨.

    }




<<짧은 파일을  RandomAccess -> MappedByteBuffer (Direct임) 로 매핑해서.. 파일의 내용을 꺼꾸로 하기..>>




            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                     

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 


   int len = ra.length();


            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                        

            //파일을 파일 채널을 이용하여 버퍼에 매핑 합니다.                        

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 

            

            int len2 = (int)ra.length(); 

            

            //파일 자체 내용을 뒤집기 

            for (int i = 0, j = len2 - 1; i < j; i++, j--) 

            { 

                byte b = mbb.get(i); 

                mbb.put(i, mbb.get(j));  //파일의 내용을 순서 바꿉니다. 

                mbb.put(j, b); 

            } 

                        

            fc.close(); 

Posted by yongary
,