// Buffer 常见方法:
// flip(): 写模式转换成读模式
// rewind() :将 position 重置为 0 ,一般用于重复读。
// clear() :清空 buffer ,准备再次被写入 (position 变成 0 , limit 变成 capacity) 。
// compact(): 将未读取的数据拷贝到 buffer 的头部位。
// mark() 、 reset():mark 可以标记一个位置, reset 可以重置到该位置。
// Buffer 常见类型: ByteBuffer 、 MappedByteBuffer 、 CharBuffer 、 DoubleBuffer 、 FloatBuffer 、 IntBuffer 、 LongBuffer 、 ShortBuffer 。
// channel 常见类型 :FileChannel 、 DatagramChannel(UDP) 、 SocketChannel(TCP) 、 ServerSocketChannel(TCP)
// 在本机上面做了个简单的性能测试。我的笔记本性能一般。 ( 具体代码可以见附件。见 nio.sample.filecopy 包下面的例子 ) 以下是参
String source = "d:/b.txt";
String dest = "d:/newnewnewnenwnwnewnewne.txt";
try
{
FileInputStream in = new FileInputStream(new File(source));
FileOutputStream out = new FileOutputStream(new File(dest));
// 获取源文件和目标文件的输入输出流
FileChannel infc = in.getChannel();
FileChannel outfc = out.getChannel();
// 创建缓冲区
ByteBuffer b = ByteBuffer.allocate(1024);
while(true) {
// clear方法重设缓冲区,使它可以接受读入的数据
b.clear();
int r = infc.read(b);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if(r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
// 写模式转换成读模式
b.flip();
outfc.write(b);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// flip(): 写模式转换成读模式
// rewind() :将 position 重置为 0 ,一般用于重复读。
// clear() :清空 buffer ,准备再次被写入 (position 变成 0 , limit 变成 capacity) 。
// compact(): 将未读取的数据拷贝到 buffer 的头部位。
// mark() 、 reset():mark 可以标记一个位置, reset 可以重置到该位置。
// Buffer 常见类型: ByteBuffer 、 MappedByteBuffer 、 CharBuffer 、 DoubleBuffer 、 FloatBuffer 、 IntBuffer 、 LongBuffer 、 ShortBuffer 。
// channel 常见类型 :FileChannel 、 DatagramChannel(UDP) 、 SocketChannel(TCP) 、 ServerSocketChannel(TCP)
// 在本机上面做了个简单的性能测试。我的笔记本性能一般。 ( 具体代码可以见附件。见 nio.sample.filecopy 包下面的例子 ) 以下是参
String source = "d:/b.txt";
String dest = "d:/newnewnewnenwnwnewnewne.txt";
try
{
FileInputStream in = new FileInputStream(new File(source));
FileOutputStream out = new FileOutputStream(new File(dest));
// 获取源文件和目标文件的输入输出流
FileChannel infc = in.getChannel();
FileChannel outfc = out.getChannel();
// 创建缓冲区
ByteBuffer b = ByteBuffer.allocate(1024);
while(true) {
// clear方法重设缓冲区,使它可以接受读入的数据
b.clear();
int r = infc.read(b);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if(r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
// 写模式转换成读模式
b.flip();
outfc.write(b);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}