标签:res oca style import 缓存 position and char port
1.FileChannel 和 Buffer
package nio._Buffer; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Demo { public static void main(String[] args) throws IOException { RandomAccessFile aFile = new RandomAccessFile("f:/zhuopeng/nioFile.txt","rw"); FileChannel fileChannel = aFile.getChannel(); RandomAccessFile aFile2 = new RandomAccessFile("f:/zhuopeng/nioFile2.txt","rw"); FileChannel fileChannel2 = aFile2.getChannel(); //分配内存,创建一个buffer,capacity为48 ByteBuffer buf = ByteBuffer.allocate(48); //1.放入缓存的方法,从channel读取 int read = fileChannel.read(buf); //2.放入缓存的方法,自己手动放进去 String str = "zhuopeng"; byte[] b = str.getBytes(); buf.put(b); while (read != -1) { //切换为读模式 buf.flip(); //标记当前的position buf.mark(); while (buf.hasRemaining()){ System.out.print((char)buf.get());//一次读取一个byte } //重新回到当前的position buf.reset(); //将buf中的内容写到另一个channel中 int write = fileChannel2.write(buf); buf.clear(); read = fileChannel.read(buf); } aFile.close(); } }
2.
标签:res oca style import 缓存 position and char port
原文地址:https://www.cnblogs.com/da-peng/p/10092430.html