您的位置:首页 > 编程语言 > Java开发

Java Nio 实现文件的传输

2014-02-25 16:08 357 查看
使用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<SelectionKey> keys=selector.selectedKeys();
Iterator<SelectionKey> 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<fileSize);
System.out.println("文件传输成功");
fic.close();
fis.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio