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

你可能感兴趣的:(JAVA总结)