压缩文件创建奇数文件存档结构

时间:2013-03-22 19:21:21

标签: java zip

当前文件位置:C:\bearCave\bear.mp3

我想将其压缩,使其在C:\bearCave中显示为bear.zip的zip文件。在bear.zip中,我只想看到没有中间文件夹的bear.mp3

换句话说,文件结构应该是:

bear.zip
 - bear.mp3

我设法压缩了文件,该文件是在正确的位置C:\bearCave生成的。有趣的是,在该zip文件中,还有另一个文件夹bearCave,其中包含我的文件:

   bear.zip
    - C: 
     - bearCave
      - bear.mp3

编辑1:可能的线索,outfilename=C:\bearCave\bear.zip

这是我的代码:

    String[] filenames = new String[]{file.getPath()};
    int dirEnd = (file.getPath()).indexOf(file.getName());
    String fileDirectory=file.getPath().substring(0, dirEnd);
    Logger.debug("dirEnd="+dirEnd);
    Logger.debug("fileDir="+fileDirectory);
    String outFilename = fileDirectory + (file.getName()).substring(0, ((file.getName()).length())-4) + ".zip";
    Logger.debug("outFile=" + outFilename);
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

    for (int i=0; i<filenames.length; i++) {
        FileInputStream in = new FileInputStream(filenames[i]);

        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(filenames[i]));

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            Logger.debug("len = " + len);
            out.write(buf, 0, len);
        }

        // Complete the entry
        out.closeEntry();
        in.close();
        Logger.debug("entry clsoed");
    }

    // Complete the ZIP file
    out.close();
    Logger.debug("zipping complete!");
} catch (IOException e) {
    Logger.error(e);
    Logger.debug(e);
}

堆栈跟踪

fileName = bear.mp3
filePath = C:\bearCave\bear.mp3
fileDir=C:\bearCave\
outFile=C:\bearCave\bear.zip
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 1024
len = 508
entry clsoed
zipping Complete!

1 个答案:

答案 0 :(得分:1)

你的filenames[]数组填充了什么?我认为问题在于这一行:

// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));

正如我所看到的,filenames[i]是文件的完整路径,ZipEntry将为您创建这种奇怪的结构,因为它将给定路径解析为其“自己的”目录结构。尝试仅使用指定的文件名创建ZipEntry(不带路径组件)。