Java 压缩文件会创建奇数文件归档结构

Java 压缩文件会创建奇数文件归档结构,java,zip,Java,Zip,当前文件位置:C:\bearCave\bear.mp3 我想压缩它,使它在C:\bearCave中显示为zip文件,如bear.zip。在bear.zip中,我只想看到没有中间文件夹的bear.mp3 换句话说,文件结构应为: bear.zip - bear.mp3 我设法压缩了文件,它是在正确的位置生成的C:\bearCave。有趣的是,在该zip文件中,还有另一个文件夹bearCave,其中包含我的文件,如下所示: bear.zip - C: - bearCav

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

我想压缩它,使它在
C:\bearCave
中显示为zip文件,如
bear.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);
}

您的
文件名[]
数组填充了什么?我认为问题在于这一行:

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

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

winrar在这里做什么?双击zip文件将我带到winrar,因为它是我的默认应用程序。Winrar告诉我档案中有一个文件夹
C:
wihtin,在另一个文件夹
bearCave
bear.mp3
OK中,所以
Winrar
与这个问题无关。另外,您可以执行这个命令
jar-tvf-bear.zip
并将输出粘贴到这里吗?
filenames=newstring[]{file.getPath()}
where file是指向
bear.mp3
file
对象,是的,那么您是否只尝试创建带有文件名的
ZipEntry
?例如,
新的ZipEntry(file.getName())
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));