package
com;
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.nio.ByteBuffer;
import
java.nio.channels.FileChannel;
public
class
Test{
public
static
void
main (String[]argv)
throws
IOException{
FileInputStream aFile =
new
FileInputStream(
"/Users/wudiyong/xxx"
);
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(
48
);
int
bytesRead = inChannel.read(buf);
while
(bytesRead != -
1
) {
System.out.println(
"Read "
+ bytesRead);
buf.flip();
while
(buf.hasRemaining()){
System.out.print((
char
) buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
}
}
import
java.io.IOException;
import
java.nio.ByteBuffer;
import
java.nio.channels.Channels;
import
java.nio.channels.ReadableByteChannel;
import
java.nio.channels.WritableByteChannel;
public
class
Test {
public
static
void
main(String[] agrs)
throws
IOException {
ReadableByteChannel source = Channels.newChannel(System.in);
WritableByteChannel dest = Channels.newChannel(System.out);
// channelCopy1(source, dest);//方式一
channelCopy2(source, dest);
//方式二
source.close();
dest.close();
}
private
static
void
channelCopy1(ReadableByteChannel src,WritableByteChannel dest)
throws
IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(
16
*
10
);
while
(src.read(buffer) != -
1
) {
buffer.flip();
dest.write(buffer);
/*
* 因为可能不能够一次把buffer全部输出,此时buffer里还有剩余的数据,需要用compact()把
* 这些数据往前移,新的数据才能从后面写入,如果一次就能完全输出,则compact的作用相当于clear
*/
buffer.compact();
}
//可能buffer里还有数据,把剩余的数据全部输出
buffer.flip();
while
(buffer.hasRemaining()) {
dest.write(buffer);
}
}
private
static
void
channelCopy2(ReadableByteChannel src,WritableByteChannel dest)
throws
IOException{
ByteBuffer buffer = ByteBuffer.allocateDirect (
16
*
10
);
while
(src.read (buffer) != -
1
) {
buffer.flip();
//循环把buffer里的所有数据都输出,再接收新的数据
while
(buffer.hasRemaining()){
dest.write (buffer);
}
buffer.clear( );
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。