本文共 1570 字,大约阅读时间需要 5 分钟。
Java通过套接字传输多个文件
好的,尝试通过套接字传输指定的文件目录,从arraylist中删除目录对象,因此只剩下文件,并在同一个套接字上逐个传输它们。这里的arraylist充满了ONLY文件,没有目录。继承人分别为客户端和服务器接收和发送代码。除了将所有数据写入第一个文件之外,代码运行正常且没有错误。后续文件在服务器文件夹中创建,但它们是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
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
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();
转载地址:https://blog.csdn.net/weixin_32290249/article/details/114920510 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!