1,代码实例
FileInputStream inputStream=new FileInputStream("input.txt");
FileOutputStream outputStream =new FileOutputStream("output.txt");
FileChannel channel1 = inputStream.getChannel();
FileChannel channel2 = outputStream.getChannel();
ByteBuffer buffer= ByteBuffer.allocate(512);
while(true)
{
buffer.clear();
int read=channel1.read(buffer);
System.out.println("read: "+read);
if(-1==read)
{
break;
}
buffer.flip();
channel2.write(buffer);
}
channel1.close();
channel2.close();
将input.txt的内容读取到output.txt
2,buffer的详解
2.1 allocate
2.2 slice方法
/**
* Creates a new byte buffer whose content is a shared subsequence of
* this buffer's content.
* 创造一个新的字节buffer和当前buffer共享buffer的content
* The content of the new buffer will start at this buffer's current
* position. Changes to this buffer's content will be visible in the new
* buffer, and vice versa; the two buffers' position, limit, and mark
* values will be independent.
*
*
The new buffer's position will be zero, its capacity and its limit
* will be the number of bytes remaining in this buffer, and its mark
* will be undefined. The new buffer will be direct if, and only if, this
* buffer is direct, and it will be read-only if, and only if, this buffer
* is read-only.
*
* @return The new byte buffer
*/
public abstract ByteBuffer slice();
ByteBuffer buffer= ByteBuffer.allocate(10);
for(int i=0;i
将2到6的内容大写
2.3 只读buffer
/**
* Creates a new, read-only byte buffer that shares this buffer's
* content.
*创造一个新的只读buffer和当前的buffer共享内容
* The content of the new buffer will be that of this buffer. Changes
* to this buffer's content will be visible in the new buffer; the new
* buffer itself, however, will be read-only and will not allow the shared
* content to be modified. The two buffers' position, limit, and mark
* values will be independent.
* 不能修改,但是两个buffer的三个属性都是独立的
*
The new buffer's capacity, limit, position, and mark values will be
* identical to those of this buffer.
*
*
If this buffer is itself read-only then this method behaves in
* exactly the same way as the {@link #duplicate duplicate} method.
*
* @return The new, read-only byte buffer
*/
public abstract ByteBuffer asReadOnlyBuffer();
2.4 allocateDirect
在buffer中
public abstract class Buffer {
/**
* The characteristics of Spliterators that traverse and split elements
* maintained in Buffers.
*/
static final int SPLITERATOR_CHARACTERISTICS =
Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;
// Invariants: mark <= position <= limit <= capacity
private int mark = -1;
private int position = 0;
private int limit;
private int capacity;
// Used only by direct buffers
为直接内容使用
// NOTE: hoisted here for speed in JNI GetDirectBufferAddress
写在这儿视为了提高获取的速率
long address;