java用NIO实现文件传输_Java Nio 实现文件的传输

该博客介绍了如何使用Java的非阻塞I/O(NIO)实现文件的传输。通过ServerSocket和ClientSocket类,详细展示了从创建ServerSocketChannel、设置非阻塞模式、接收客户端连接到使用ReceiveAndSend类进行文件的接收和发送的过程。
摘要由CSDN通过智能技术生成

使用Java Nio实现文件的传输

1、ServerSocket.java

package ch2;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel.MapMode;

import java.nio.channels.FileChannel;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

import java.util.Set;

public class ServerSocket {

public static void main(String[] args) throws Exception {

int port = 10000;

//打开服务器套接字通道

ServerSocketChannel ssc = ServerSocketChannel.open();

//创建一个选择器

Selector selector = Selector.open();

//设置非阻塞模式

ssc.configureBlocking(false);

InetSocketAddress address = new InetSocketAddress(port);

//绑定监听端口

ssc.bind(address);

//注册选择器,保持等待模式

ssc.register(selector, SelectionKey.OP_ACCEPT);

System.out.println("服务器已开启,端口:"+port);

while(true){

selector.select();

//返回此选择器的已选择键集

Set keys=selector.selectedKeys();

Iterator iterKey=keys.iterator();

while(iterKey.hasNext()){

SelectionKey sk=iterKey.next();

//测试此键的通道是否已准备好接受新的套接字连接

if(sk.isAcceptable()){

SocketChannel sc=ssc.accept();

try {

//接收

new ReceiveAndSend().receiveFile(sc);

sc.close();

} catch (Exception e) {

}

}

}

}

}

}

ClientSocket.java

package ch2;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.SocketChannel;

public class ClientSocket {

public static void main(String[] args) throws Exception {

int port=10000;

String ip = "localhost";

//打开传输通道

SocketChannel sc = SocketChannel.open();

//连接

sc.connect(new InetSocketAddress(ip,port));

//发送文件

new ReceiveAndSend().sendFile(sc, "e:"+File.separator+"node.txt","node.txt");

//关闭传输通道

sc.close();

}

}

ReceiveAndSend.java

package ch2;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

public class ReceiveAndSend {

/**

* 接收文件

* @param sc

* @throws IOException

*/

public void receiveFile(SocketChannel sc) throws IOException{

//获取保存文件

File file=new File("e:"+File.separator+"mmm.txt");

FileOutputStream fos=new FileOutputStream(file);

//获取通道

FileChannel foc = fos.getChannel();

//设置接收消息体缓冲区

ByteBuffer bb=ByteBuffer.allocateDirect(1024);

//设置接收消息头缓冲区

ByteBuffer headByte=ByteBuffer.allocateDirect(32);

//接收消息头

sc.read(headByte);

byte[] b=new byte[32];

headByte.flip();

for (int i = 0; headByte.hasRemaining(); i++) {

b[i]=headByte.get();

}

headByte.clear();

//获取文件信息

String fileInfo=new String(b,Charset.forName("UTF-8"));

String[] strInfo=fileInfo.split("\\|");

System.out.println("文件:"+strInfo[0]+"--大小:"+strInfo[1]);

int read=sc.read(bb);

while(read!=-1){

bb.flip();

//写入到输出通道

foc.write(bb);

bb.clear();

read=sc.read(bb);

}

foc.close();

fos.close();

}

/**

* 发送文件

* @param sc

* @param path

* @param fileName

* @throws IOException

*/

public void sendFile(SocketChannel sc,String path,String fileName) throws IOException{

File file=new File(path);

FileInputStream fis = new FileInputStream(file);

FileChannel fic = fis.getChannel();

ByteBuffer bb = ByteBuffer.allocateDirect(1024);

ByteBuffer headbb = ByteBuffer.allocateDirect(32);

int read=0;

long fileSize = file.length();

long sendSize=0;

System.out.println("文件大小:"+fileSize);

//拼接头信息

String head=fileName+"|"+fileSize+"|;";

//将头信息写入缓冲区

headbb.put(head.getBytes(Charset.forName("UTF-8")));

int c=headbb.capacity()-headbb.position();

//填满头信息

for (int i = 0; i < c; i++) {

headbb.put(";".getBytes(Charset.forName("UTF-8")));

}

headbb.flip();

//将头信息写入到通道

sc.write(headbb);

do{

//将文件写入到缓冲区

read = fic.read(bb);

sendSize+=read;

bb.flip();

//将文件写入到通道

sc.write(bb);

bb.clear();

System.out.println("已传输/总大小:"+sendSize+"/"+fileSize);

}while(read!=-1&&sendSize

System.out.println("文件传输成功");

fic.close();

fis.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值