java 套接字传文件_Java多文件传输通过套接字

好的,尝试通过套接字传输指定的文件目录,从数组列表中删除目录对象,因此只剩下文件,并通过相同的套接字将它们传输1。这里的arraylist中只填有文件,没有目录。分别接收和发送客户端和服务器的代码。代码运行良好,没有错误,除了所有的数据正在写入第一个文件。随后的文件在服务器文件夹中创建,但是它们是0字节。任何输入将不胜感激。

这是接收文件的服务器代码

public void receive(){

try {

DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

//read the number of files from the client

int number = dis.readInt();

ArrayListfiles = new ArrayList(number);

System.out.println("Number of Files to be received: " +number);

//read file names, add files to arraylist

for(int i = 0; i< number;i++){

File file = new File(dis.readUTF());

files.add(file);

}

int n = 0;

byte[]buf = new byte[4092];

//outer loop, executes one for each file

for(int i = 0; i < files.size();i++){

System.out.println("Receiving file: " + files.get(i).getName());

//create a new fileoutputstream for each new file

FileOutputStream fos = new FileOutputStream("C:\\users\\tom5\\desktop\\salestools\\" +files.get(i).getName());

//read file

while((n = dis.read(buf)) != -1){

fos.write(buf,0,n);

fos.flush();

}

fos.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

这是用于发送文件的客户代码

public void send(ArrayListfiles){

try {

DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

System.out.println(files.size());

//write the number of files to the server

dos.writeInt(files.size());

dos.flush();

//write file names

for(int i = 0 ; i < files.size();i++){

dos.writeUTF(files.get(i).getName());

dos.flush();

}

//buffer for file writing, to declare inside or outside loop?

int n = 0;

byte[]buf = new byte[4092];

//outer loop, executes one for each file

for(int i =0; i < files.size(); i++){

System.out.println(files.get(i).getName());

//create new fileinputstream for each file

FileInputStream fis = new FileInputStream(files.get(i));

//write file to dos

while((n =fis.read(buf)) != -1){

dos.write(buf,0,n);

dos.flush();

}

//should i close the dataoutputstream here and make a new one each time?

}

//or is this good?

dos.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值