我想在网络上发送文件夹,根据我的代码,如果文件夹包含成功发送的文件,但如果文件夹包含内部文件夹,它不会在客户端创建文件夹?
服务器代码:
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();
}
}
它不显示任何错误,而是在客户端创建名称(服务器端的文件夹)的匿名文件。请告诉我我的代码有什么问题!
答案 0 :(得分: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, "")
或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();
}