发布时间 : 星期二 文章网络文件传输设计报告更新完毕开始阅读8e3529a2bcd126fff6050b3f
import java.nio.ByteBuffer;
public class FileUtil {
private byte FileInfo = 0x1; ///文件信息上传命令
private byte FileDB = 0x2; ///文件数据传输命令
private int BlockSize = 512; ///规定文件块大小为512
public byte[] getFileInfoPack(String FileName, int FileSize) {
ByteBuffer buf = ByteBuffer.allocate(260); //分配一个新的字节缓冲区
byte[] infopack = new byte[260];
byte[] filename = new byte[255];
System.arraycopy(FileName.getBytes(), 0, filename, 0,
FileName.length()); //从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
buf.clear();
buf.put(FileInfo); //相对put方法(可选操作),将给定的字节写入此缓冲区的当前位置,然后该位置递增。
buf.putInt(FileSize); //用于写入 int 值的相对 put 方法(可选操作),
//将 4 个包含给定 int 值的字节按照当前的字节顺序写入到
此缓冲区的当前位置,然后将该位置增加 4。
buf.put(filename);
buf.flip();
buf.get(infopack);//此方法将此缓冲区的字节传输到给定的目标数组中
buf.compact();//将缓冲区的当前位置和界限之间的字节(如果有)复制到缓冲区的开始处
return infopack; }
public byte[] getFileDB(int index, int blocksize, byte[] data) {
byte[] filedb = new byte[9 + blocksize]; //对文件本身的传输过程定义
ByteBuffer buf = ByteBuffer.allocate(9 + blocksize);
buf.clear();
buf.put(this.FileDB);
buf.putInt(index);
buf.putInt(blocksize);
buf.put(data,0,blocksize);
buf.flip();
buf.get(filedb);
buf.compact();
return filedb; }
public int getBlockSize(){
return this.BlockSize; } } /*
*文件接受端线程的过程。
*/
import java.nio.channels.SocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.ByteBuffer;
import java.io.RandomAccessFile;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
public class ReveiceThread extends Thread {
private FileUtil util = new FileUtil();
/*
* 针对面向流的连接套接字的可选择通道。
*/
private SocketChannel r_channel = null; //
private ByteBuffer buf = ByteBuffer.allocate(util.getBlockSize() + 9); //
public ReveiceThread(SocketChannel channel) throws Exception {
this.r_channel = channel;
this.r_channel.configureBlocking(false); }
public void run() {
try {
Selector selector = Selector.open();
SelectionKey key = r_channel.register(selector, SelectionKey.OP_READ);
buf.clear();
File file = null;
FileOutputStream fout = null;//文件输出流对象
RandomAccessFile raf = null;//创建临时文件对象