1

I'm having an issue zipping up folders.

I.e. I'll have a folder like this

C:\Lazy\Test

containing files File1.cpp, File2.hpp,.. etc

The zipped up folder looks like C:\Lazy\Test.zip -> Lazy\Test which contains all the cpp and hpp files.

I want to remove the extra subfolders (Lazy\Test) that get created. Why is this happening?

In other words, the zipped up files are not directly underneath the zip file, I have to navigate two more folders to get to them.

Where can I find this issue in the code?

    private void zipDirectory() {

       File lazyDirectory = new File(defaultSaveLocation);

       File[] files = lazyDirectory.listFiles();

       for (File file : files) {

          if (file.isDirectory()) {
            System.out.println("Zipping up " + file);
            zipContents(file);
            }
        }       
    }


public static void addToZip(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

    System.out.println("Writing '" + fileName + "' to zip file");

    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);

    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();

    }

public static void zipContents(File dirToZip) {

    List<File> fileList = new ArrayList<File>();

    File[] filesToZip = dirToZip.listFiles();

    for (File zipThis : filesToZip) {

        String ext = "";

        int i = zipThis.toString().lastIndexOf('.');

        if (i > 0) {
            ext = zipThis.toString().substring(i+1);
        }

        if(ext.matches("cpp|bem|gz|h|hpp|pl|pln|ppcout|vec|xml|csv")){
            fileList.add(zipThis);
        }

    }


    try {
        FileOutputStream fos = new FileOutputStream(dirToZip.getName() + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        for (File file : fileList) {

            addToZip(file.toString(), zos);

        }

      } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
    }
4

1 回答 1

1

更改addToZip文件以获取File对象。用它来打开文件流,但只File#getName用来创建ZipEntry,如下...

public static void addToZip(File file, ZipOutputStream zos) throws FileNotFoundException, IOException {

    System.out.println("Writing '" + fileName + "' to zip file");

    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(file.getName());
    zos.putNextEntry(zipEntry);

    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();

}
于 2013-06-12T00:44:11.677 回答