一堆嵌套的文件夹   只有文件夹   没有文件
我用了下面代码压缩出来的总是一个0KB的损坏的文件   问题出在哪里?   在线等
感觉好像只能压缩文件   不能压缩文件夹private static void writeZipOutputStream(final ZipOutputStream out,
             final File targetFile, final String rootPath) throws IOException {
     LOG.info("writeZipOutputStream is called.");
     if (targetFile.isDirectory()) {
         File[] files = targetFile.listFiles();
         for (File file : files) {
             writeZipOutputStream(out, file, rootPath);
             try {
                 Thread.sleep(10);
             } catch (InterruptedException e) {
                 LOG.warn(e.getMessage(), e);
             }
         }
     } else {
         ZipEntry target = new ZipEntry(targetFile.getPath().replaceAll(
                 "\\\\", "/").substring(rootPath.length()));
         out.putNextEntry(target);
         byte[] buf = new byte[1024];
         int count;
         BufferedInputStream in = new BufferedInputStream(
                 new FileInputStream(targetFile));
         while ((count = in.read(buf, 0, 1024)) != -1) {
             out.write(buf, 0, count);
         }
         in.close();
         out.closeEntry();
     }
}

解决方案 »

  1.   


    targetFile.isDirectory()这句不是一直判断是不是文件夹,是的话递归?
    那么递归到最里面一层怎么处理了?没找到文件跳出了还是把最里面一层最为目录走else了?
    如果有空的话麻烦帮忙看一下代码谢谢
      

  2.   

    修改后的代码if (targetFile.isDirectory()) {
                File[] files = targetFile.listFiles();
                if (files.length == 0) {
                    ZipEntry target = new ZipEntry(targetFile.getPath().replaceAll(
                            "\\\\", "/").substring(rootPath.length()) + "/");
                    out.putNextEntry(target);
                    out.closeEntry();
                } else {
                    for (File file : files) {
                        writeZipOutputStream(out, file, rootPath);                    try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            LOG.warn(e.getMessage(), e);
                        }
                    }
                }
            } else {
                ZipEntry target = new ZipEntry(targetFile.getPath().replaceAll(
                        "\\\\", "/").substring(rootPath.length()));
                out.putNextEntry(target);
                byte[] buf = new byte[1024];
                int count;
                BufferedInputStream in = new BufferedInputStream(
                        new FileInputStream(targetFile));
                while ((count = in.read(buf, 0, 1024)) != -1) {
                    out.write(buf, 0, count);
                }            in.close();
                out.closeEntry();
            }