//标记位置 privateint mark = -1; //当前进行读写操作的数据元素的位置 privateint position = 0; //缓冲区数组中进行读写操作的最大允许位置,limit<=capacity privateint limit; //缓冲区数组的总长度,创建时指定的 privateint capacity;
publicfinalintcapacity(){ return capacity; }
publicfinalintposition(){ return position; }
publicfinal Buffer position(int newPosition){ if ((newPosition > limit) || (newPosition < 0)) thrownew IllegalArgumentException(); position = newPosition; if (mark > position) mark = -1; returnthis; }
publicfinalintlimit(){ return limit; }
publicfinal Buffer limit(int newLimit){ if ((newLimit > capacity) || (newLimit < 0)) thrownew IllegalArgumentException(); limit = newLimit; if (position > newLimit) position = newLimit; if (mark > newLimit) mark = -1; returnthis; }
// 将当前位置进行标记 publicfinal Buffer mark(){ mark = position; returnthis; } // 使用reset方法可以将读写位置回到mark的位置上 publicfinal Buffer reset(){ int m = mark; if (m < 0) thrownew InvalidMarkException(); position = m; returnthis; }
//将读写位置置为0 // 读写限制为容量 // 标记恢复-1 publicfinal Buffer clear(){ position = 0; limit = capacity; mark = -1; returnthis; }
// 将读写限制设为当前位置 // 读写位置设为0 // 标记恢复-1 publicfinal Buffer flip(){ limit = position; position = 0; mark = -1; returnthis; }
// 读写位置设为0 // 标记恢复-1 publicfinal Buffer rewind(){ position = 0; mark = -1; returnthis; }
FileChannel fileChannel = new FileOutputStream(FILE).getChannel() FileChannel fileChannel = new RandomAccessFile(FILE,"rw").getChannel() FileChannel fileChannel = new FileInputStream(FILE).getChannel()
文件传输
可以直接使用transferFrom、transferTo传输方法来快速的传输数据
1 2 3 4 5 6 7 8
// 从src源通道中的数据写入当前文件通道 publicabstractlongtransferFrom(ReadableByteChannel src, long position, long count) throws IOException; // 从当前文件通道中的数据写入target通道 publicabstractlongtransferTo(long position, long count, WritableByteChannel target) throws IOException;
主线程睡眠 线程准备写 java.io.IOException: 另一个程序已锁定文件的一部分,进程无法访问。 at sun.nio.ch.FileDispatcherImpl.write0(Native Method) at sun.nio.ch.FileDispatcherImpl.write(FileDispatcherImpl.java:75) at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) at sun.nio.ch.IOUtil.write(IOUtil.java:65) at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:211) at com.zhanghe.study.io.nio.FileLockTest$1.run(FileLockTest.java:35) at java.lang.Thread.run(Thread.java:745) 主线程准备写