e170. writing to a channel with a bytebuffer.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 49 行

TXT
49
字号
It is necessary to use a ByteBuffer to write to a channel. This example retrieves bytes from an input stream and writes them to a channel using a ByteBuffer. The tricky part of this operation is to remember to properly set the buffer's position before and after a write. 
    try {
        // Obtain a channel
        WritableByteChannel channel = new FileOutputStream("outfilename").getChannel();
    
        // Create a direct ByteBuffer;
        // see also e158 Creating a ByteBuffer
        ByteBuffer buf = ByteBuffer.allocateDirect(10);
    
        byte[] bytes = new byte[1024];
        int count = 0;
        int index = 0;
    
        // Continue writing bytes until there are no more
        while (count >= 0) {
            if (index == count) {
                count = inputStream.read(bytes);
                index = 0;
            }
            // Fill ByteBuffer
            while (index < count && buf.hasRemaining()) {
                buf.put(bytes[index++]);
            }
    
            // Set the limit to the current position and the position to 0
            // making the new bytes visible for write()
            buf.flip();
    
            // Write the bytes to the channel
            int numWritten = channel.write(buf);
    
            // Check if all bytes were written
            if (buf.hasRemaining()) {
                // If not all bytes were written, move the unwritten bytes
                // to the beginning and set position just after the last
                // unwritten byte; also set limit to the capacity
                buf.compact();
            } else {
                // Set the position to 0 and the limit to capacity
                buf.clear();
            }
        }
    
        // Close the file
        channel.close();
    } catch (Exception e) {
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?