java用NIO实现文件传输_JAVA、NIO的文件传输案例

使用Java的Nio流进行文件传输案例。

FileReceiver

package com.nio.demo;

import java.io.File;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.EnumSet;

public class FileReceiver {

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

FileReceiver fileSender = new FileReceiver();

SocketChannel clientSocket = fileSender.createSocketChannel();

fileSender.recFile(clientSocket);

}

/**

* 创建流渠道

*

* @return

* @throws IOException

*/

private SocketChannel createSocketChannel() throws IOException {

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.bind(new InetSocketAddress(8081));

SocketChannel clientSocket = serverSocketChannel.accept();

System.out.println("Connection Client " + clientSocket.getRemoteAddress());

return clientSocket;

}

/**

* 发送文件

*

* @param sendChannel

* @throws IOException

*/

private void recFile(SocketChannel clientSocket) throws IOException {

// 发送文件流

ByteBuffer buffer = ByteBuffer.allocate(256);

StringBuffer fileName = new StringBuffer("rec_");

int readLength = 0;

while ((readLength = clientSocket.read(buffer)) > 0) {

buffer.flip();

fileName.append(new String(buffer.array()));

buffer.clear();

// 最后一包读取特殊处理,不然会一直等待读入

if (readLength != buffer.capacity()) {

break;

}

}

// 接收文件名称

String filePath = "D:/temp/";

File saveDir = new File(filePath);

if (!saveDir.exists()) {

saveDir.mkdirs();

}

filePath = filePath + fileName.toString().trim();

System.out.println("Received File name " + fileName.toString());

// response getFile Name succ

clientSocket.write(ByteBuffer.wrap(new String("0000").getBytes()));

// 文件获取

Path path = Paths.get(filePath);

FileChannel fileChannel = FileChannel.open(path,

EnumSet.of(StandardOpenOption.CREATE,

StandardOpenOption.TRUNCATE_EXISTING,

StandardOpenOption.WRITE));

// 写入到本地

while (clientSocket.read(buffer) >= 0) {

buffer.flip();

fileChannel.write(buffer);

buffer.clear();

}

fileChannel.close();

System.out.println("Received Remote File Succ!");

clientSocket.close();

}

}

FileSender

package com.nio.demo;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.SocketChannel;

import java.nio.file.Path;

import java.nio.file.Paths;

/**

* 发送文件Demo

*/

public class FileSender {

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

FileSender fileSender = new FileSender();

SocketChannel sendChannel = fileSender.createSocketChannel();

String filePath = "D:/temp/1.jpg";

fileSender.sendFileAndName(sendChannel, filePath);

}

/**

* 发送文件

*

* @param sendChannel

* @throws IOException

*/

private void sendFileAndName(SocketChannel clientChannel, String filePath) throws IOException {

// 发送文件流

clientChannel.write(ByteBuffer.wrap(new String("1.jpg").getBytes()));

ByteBuffer buffer = ByteBuffer.allocate(6);

StringBuffer answerCode = new StringBuffer();

int length = 0;

while ((length = clientChannel.read(buffer)) != -1) {

buffer.flip();

answerCode.append(new String(buffer.array()));

if (length != buffer.capacity()) {

break;

}

buffer.clear();

}

System.out.println("server answer is " + answerCode.toString().trim());

if (answerCode.toString().trim().equals("0000")) {

sendFile(clientChannel, filePath);

} else {

System.out.println("rec server answer error");

clientChannel.close();

}

}

/**

* 创建流渠道

*

* @return

* @throws IOException

*/

private SocketChannel createSocketChannel() throws IOException {

SocketChannel sendChannel = SocketChannel.open();

sendChannel.connect(new InetSocketAddress("localhost", 8081));

return sendChannel;

}

/**

* 发送文件

*

* @param sendChannel

* @throws IOException

*/

private void sendFile(SocketChannel sendChannel, String filePath) throws IOException {

// 发送文件流

Path path = Paths.get(filePath);

FileChannel fileChannel = FileChannel.open(path);

ByteBuffer buffer = ByteBuffer.allocate(1024);

while (fileChannel.read(buffer) != -1) {

buffer.flip();

sendChannel.write(buffer);

buffer.clear();

}

sendChannel.close();

}

}

对源码不理解的可以私信,大家一起学习。

源码下载地址:http://download.csdn.net/download/zhanghua1369/10270176

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值