2

Current file location: C:\bearCave\bear.mp3

I want to zip it such that it will appear as a zip file in C:\bearCave as bear.zip. In bear.zip, I just want to see bear.mp3 with no intermediary folders.

In other words, file structure should be:

bear.zip
 - bear.mp3

I managed to zip the file, which is generated in the correct location C:\bearCave. Interestingly, within that zip file, there is another folder bearCave which contains my file like so:

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

EDIT 1: A possible clue, outfilename=C:\bearCave\bear.zip

Here's my code:

    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);
}

Stacktrace

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!
4

1 回答 1

1

what's your filenames[] array populated with? I think the problem is this line:

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

As I see it, filenames[i] is the whole path to your file and the ZipEntry will create this strange structure for you since it parses the given path into its "own" directory structure. Try creating the ZipEntry only with the designated filename (without the path component).

于 2013-03-22T19:48:37.960 回答