0

我想在网络上发送文件夹,根据我的代码,如果文件夹包含成功发送它们的文件,但如果文件夹包含内部文件夹,它不会在客户端创建文件夹?

服务器代码:

ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
File file = new File("home/");
File[] children = file.listFiles();

if (children != null) {
  for (File child : children) {
    all.add(child);  

    if(!child.isDirectory()){
      oos.writeObject(child.getName());
      FileInputStream fis = new FileInputStream(child);  

      while ((bytesRead = fis.read(buffer)) > 0) {  
        oos.writeObject(bytesRead);  
        oos.writeObject(Arrays.copyOf(buffer, buffer.length));  
      }   

    }
  }
}

客户代码:

oos = new ObjectOutputStream(theSocket.getOutputStream());
ois = new ObjectInputStream(theSocket.getInputStream());

out = new PrintWriter(theSocket.getOutputStream( ));

while (true) {
  Object o = ois.readObject();

  File file = new File(o.toString());

  if(file.isDirectory())
    File Dir = new File("new/").mkdir();
  if(!file.isDirectory()){
    FileOutputStream fos = new FileOutputStream(o.toString());    

    do {  
      o = ois.readObject();
      bytesRead = (Integer) o;
      o = ois.readObject();  
      buffer = (byte[])o;  

      fos.write(buffer, 0, bytesRead);  
    }
    while (bytesRead == BUFFER_SIZE);  
    fos.close(); 
  }
}

它不显示任何错误,而是在客户端创建一个名称为匿名的文件(服务器端的文件夹)。请告诉我我的代码有什么问题!

4

1 回答 1

0

我认为(部分)你的答案是递归。有几种方法可以做到这一点。一种是发送 bytesRead 作为目录的 -1 或 NULL 并在客户端进行递归,另一种,我将在下面展示(有点低效)是发送文件的相对路径并根据需要创建目录客户端。

服务器端:

void processFile(File file, String path)
{
  if (file.isDirectory())
  {
    File[] children = file.listFiles();
    for (File child : children)
    {
      all.add(child);
      processFile(child, path + file.getName() + "/");
    }
  }
  else
  {
    oos.writeObject(path + child.getName());
    FileInputStream fis = new FileInputStream(child);  
    while ((bytesRead = fis.read(buffer)) > 0)
    {  
      oos.writeObject(bytesRead);  
      oos.writeObject(buffer);  
    }
    oos.writeObject(BUFFER_SIZE);
  }
}

processFile(file, "")用or调用processFile(file, "/")

在通话后说一些类似oos.writeObject("")的话,并在客户端进行检查,类似于name.length() == 0知道何时停止。

客户端:

while (true)
{
  String name = (String)ois.readObject();
  if (name.length() == 0) break;
  // "/new/" is the absolute path of the directory where you want all these files to be created
  name += "/new/";

  File dir = new File(name.substring(0, name.lastIndexOf('/')));
  if (!dir.exists())
    dir.mkdirs();

  FileOutputStream fos = new FileOutputStream(new File(name));    

  bytesRead = (Integer) ois.readObject();
  while (bytesRead != BUFFER_SIZE)
  {  
    buffer = (byte[])ois.readObject();
    fos.write(buffer, 0, bytesRead);  
    bytesRead = (Integer) ois.readObject();
  }
  fos.close(); 
}
于 2012-12-28T13:40:13.890 回答