날짜별 글 목록: 2008년 6월 13일

파일에 락 걸기..

try {
        File file = new File(“filename”);
        FileChannel channel = new RandomAccessFile(file, “rw”).getChannel();

        FileLock lock = channel.lock();
        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }

        lock.release();

        channel.close();
        
}catch(Exception e){
}

Convert interchangeably between a ByteBuffer and a byte array

1. create a ByteBuffer from a byte array

byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes); 

2. retrieve bytes between the position and limit

bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);
buffer.clear(); 

3. retrieve all bytes in the buffer

bytes = new byte[buffer.capacity()];
buffer.get(bytes, 0, bytes.length);