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

使用java NIO实现复制文件

2013-12-30 01:09 288 查看
前几天自己在做一个小实验来着,突然想到自己以前通过TCP(socket)的方式做过复制文件的事情,然后就想到貌似没试过UDP(DatagramSocket)的方式实现复制文件(其实这从头就是个错误的思路)。遂马上动手试验,理所当然的写到后面就发现这样的方式有缺陷(UDP本身特性决定了),但是在思索有不有其他的变通的方式实现的时候,无意中看到了NIO这个以前一直没注意的东西,当时还想通过NIO找一些变通方式,但是看着看着觉得NIO很有意思。例如,这个实现本地复制文件的方法

FileChannel src=new FileInputStream(new File(pathName_from)).getChannel();
FileChannel dst=new FileOutputStream(new File(pathName_to)).getChannel();
dst.transferFrom(src, 0, src.size());


可能很多人以前都知道和使用过NIO的很多特性,但是我以前真是没接触过所以受到触动,就学习了更多NIO的东西,然后就实现了下面的这个程序。
服务端:

package com.googlefans.NIO;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
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;

public class NIOCopyServer implements Runnable{

private FileChannel channel_to;
private Selector selector;

@SuppressWarnings("resource")
public NIOCopyServer(int port) throws IOException{
selector=Selector.open();
ServerSocketChannel serverChannel=ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),port));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
channel_to=new FileOutputStream("E:\\testTo.txt").getChannel();
}

@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
selector.select();
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
ByteBuffer inBuffer=ByteBuffer.allocate(1024);
if(it.hasNext()){
SelectionKey key=it.next();
it.remove();
if(key.isAcceptable()){
ServerSocketChannel server=(ServerSocketChannel)key.channel();
SocketChannel channel=server.accept();
channel.configureBlocking(false);
while(channel.read(inBuffer)!=-1){
inBuffer.flip();
channel_to.write(inBuffer);
inBuffer.compact();
}
System.out.println("服务器端复制完毕!");
}else if(key.isReadable()){
read(key);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

public void read(SelectionKey key) throws IOException{
SocketChannel channel=(SocketChannel)key.channel();
ByteBuffer byteBuf=ByteBuffer.allocateDirect(1024);
channel.read(byteBuf);
byte[] data=byteBuf.array();
String msg=new String(data).trim();
System.out.println("服务器端收到信息:"+msg);
}

}



客户端:

package com.googlefans.NIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOCopyClient implements Runnable{

private Selector selector;
private FileChannel channel_from;

@SuppressWarnings("resource")
public NIOCopyClient(InetAddress ip,int port) throws IOException{
selector=Selector.open();
SocketChannel channel=SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(ip,port));
channel.register(selector, SelectionKey.OP_CONNECT);
channel_from=new FileInputStream(new File("E:\\testFrom.txt")).getChannel();
}

@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
selector.select();
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
ByteBuffer outBuffer=ByteBuffer.allocate(1024);
if(it.hasNext()){
SelectionKey key=it.next();
it.remove();
if(key.isConnectable()){
SocketChannel channel=(SocketChannel)key.channel();
if(channel.isConnectionPending()){
channel.finishConnect();
}
channel.configureBlocking(false);
while(channel_from.read(outBuffer)!=-1){
outBuffer.flip();
channel.write(outBuffer);
outBuffer.compact();
}
System.out.println("客户端上传完毕!");
}else if(key.isReadable()){
read(key);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public void read(SelectionKey key) throws IOException{
SocketChannel channel=(SocketChannel)key.channel();
ByteBuffer bb=ByteBuffer.allocate(1024);
channel.read(bb);
byte[] bytes=bb.array();
String msg=new String(bytes).trim();
System.out.println("客户端收到信息:"+msg);
}
}



实现类:


package com.googlefans.NIO;

import java.io.IOException;
import java.net.InetAddress;

public class NIOCopy {

private final static int PORT=5111;
public static void main(String[] args){
try {
Thread server=new Thread(new NIOCopyServer(PORT));
Thread client=new Thread(new NIOCopyClient(InetAddress.getLocalHost(), PORT));
server.start();
client.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



[size=large]当然我这段程序还是有很多不令人满意的地方,比如read()方法。还是希望各位ITeye的大牛们多多指导。[/size]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: