使用Channel进行本地文件读写的简单实例2

使用一个缓冲区进行读写操作:

 public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel channel01 = fileInputStream.getChannel();

FileOutputStream fileOutputStream=new FileOutputStream("2.txt");
FileChannel channel02 = fileOutputStream.getChannel();

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

//循环读取
while(true){
//清理缓冲区 非常重要
byteBuffer.clear();
int read= channel01.read(byteBuffer);
if(read==-1){
break;
}
byteBuffer.flip();
channel02.write(byteBuffer);
}
fileInputStream.close();
fileOutputStream.close();
}
直接通过channel进行读写
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("d:\\eva.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("d:\\eva2.jpg");
FileChannel channel01 = fileInputStream.getChannel();
FileChannel channel02 = fileOutputStream.getChannel();
channel02.transferFrom(channel01,0,channel01.size());
channel01.close();
channel02.close();
fileInputStream.close();
fileOutputStream.close();

}
通过buffer数组进行读写
public static void main(String[] args) throws IOException {
//使用ServerSocket和socketChannel
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
InetSocketAddress inetAddress=new InetSocketAddress(7000);
//绑定端口到socket并启动
serverSocketChannel.socket().bind(inetAddress);
//创建buffer[]数组
ByteBuffer[] byteBuffers = new ByteBuffer[2];
byteBuffers[0]=ByteBuffer.allocate(5);
byteBuffers[1]=ByteBuffer.allocate(3);
//等待客户端连接
SocketChannel socketChannel=serverSocketChannel.accept();
int messageLength=8; //假定从客户端接收8个字节
//循环读取
while (true){
int byteRead=0;
while(byteRead<messageLength){
long read=socketChannel.read(byteBuffers);
byteRead+=read;
System.out.println(byteRead);
}
//将所有的buffer进行flip
Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());
//数据读出显示到客户端
long writeByte=0;
while(writeByte<messageLength){
long write=socketChannel.write(byteBuffers);
writeByte+=write;
}
//复位操作
Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
}
}
posted @ 2020-05-12 16:12  第十八使徒  阅读(381)  评论(0)    收藏  举报