将文件夹压缩为Zip文件

时间:2013-08-22 09:21:35

标签: java file

我有这种Java方法来上传文件。我试图通过将该文件夹压缩为zip文件并上传它来尝试上传文件夹的用户。出于某种原因,在我的情况下,file.isDirectory()file.isFile()无法正常工作..即使文件名不包含任何扩展名,file.isFile()也会返回true,isDirectory()将返回false。同样directory.list()也会因为返回null而表现得很奇怪。

可能是什么问题?我做错了吗?

public File uploadFile(FileItem item, String filename, int ticket_id) throws IOException
{
    FileOutputStream out = null;
    InputStream fileContent = null;
    File file = null;

    try
    {
        //fullpath returns C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test

        StringBuffer fullPath = new StringBuffer();
        fullPath.append(Attachment.attachments_path); 
        fullPath.append("t"); 
        fullPath.append(Integer.toString(ticket_id)); 
        fullPath.append(File.separator);
        fullPath.append(filename);

        System.out.println("filename " + filename);

        file = new File(fullPath.toString());

        if (!file.exists())
        {
            // if directory does not exist, create it
            file.getParentFile().mkdirs();
        }

        if (file.isFile())
        {
            // if file is not a folder                  
            out = new FileOutputStream(file);
            fileContent = item.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            // read all the file and write it to created file
            while ((read = fileContent.read(bytes)) != -1) 
            {
                out.write(bytes, 0, read);
            }
        }
        else if (file.isDirectory())
        {
            ZipFile appZip = new ZipFile(fullPath.toString());
            appZip.generateFileList(file);
            appZip.zipIt(filename + ".zip");
        }
    }
    catch (FileNotFoundException e)
    {
        LogFile.logError("[FileUpload.uploadFile()] " + e.getMessage());
    }
    catch (IOException e1)
    {
        LogFile.logError("[FileUpload.uploadFile()] " + e1.getMessage());
    }
    finally
    {
        if (out != null)
        {
            out.close();
        }

        if (fileContent != null)
        {
            fileContent.close();
        }
    }

    return file;
}

这是我正在使用的ZipFile类

public class ZipFile 
{
    List<String> fileList = null;
    String source_folder = "";

    public ZipFile(String source_folder)
    {
        fileList = new ArrayList<String>();
        this.source_folder = source_folder;
    }

    public void zipIt(String zipFile)
    {
        byte[] buffer = new byte[1024];
        String source = "";

        try
        {
            try
            {                     
                source = source_folder.substring(source_folder.lastIndexOf("\\") + 1, source_folder.length());
            }
            catch(Exception e)
            {
                source = source_folder;
            }

            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (String file : this.fileList)
            {
                ZipEntry ze = new ZipEntry(source + File.separator + file);
                zos.putNextEntry(ze);

                FileInputStream in = new FileInputStream(source_folder + File.separator + file);

                int len;
                while ((len = in.read(buffer)) > 0)
                {
                    zos.write(buffer, 0, len);
                }

                in.close();
            }

            zos.closeEntry();
            //remember close it
            zos.close();
        } 
        catch(IOException ex)
        {
           ex.printStackTrace();   
        }
    }

    public void generateFileList(File node)
    {
        // add file only
        if(node.isFile())
        {           
            fileList.add(generateZipEntry(node.toString()));
        }

        if(node.isDirectory())
        {           
            String[] subNode = node.list();

            if (subNode != null) {

                for(String filename : subNode)
                {
                    generateFileList(new File (node, filename));
                }
            }
        }
    }

    private String generateZipEntry(String path)
    {
        return path.substring(source_folder.length() + 1, path.length());
    }
}

file.list()正在generateFileList课程的ZipFile方法中完成。我知道这是返回null,因为我尝试使用filename.indexOf(".")代替isDirectory()isFile()来检测文件是文件夹还是文件,因为它们不起作用。但我希望我对此有一个解释。

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

if (!file.exists()) {
    // if directory does not exist, create it
    file.mkdirs();
}

将创建目录并测试file.isDirectory()将返回true

答案 1 :(得分:0)

这可能是路径的问题?

C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test

你正在用斜杠混合反斜杠......

答案 2 :(得分:0)

我测试了你的代码块

ZipFile appZip = new ZipFile(file.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");

使用本地文件夹,它工作正常。我认为你正在传递一条无效的道路。这可能是导致 isFile isDirectory 方法行为奇怪的原因。尝试使用 File API在 generateFileList 方法的开头添加验证语句:

if(!node.exists) {
     // return some flag to signify error OR throw a suitable Exception   
}

这应该有效。

答案 3 :(得分:0)

    public String compressData(String srcDir) {

         String zipFile = srcDir+".zip"; 
                try {

                    // create byte buffer
                    byte[] buffer = new byte[1024];

                    FileOutputStream fos = new FileOutputStream(zipFile);

                    ZipOutputStream zos = new ZipOutputStream(fos);

                    File dir = new File(srcDir);

                    File[] files = dir.listFiles();

                    for (int i = 0; i < files.length; i++) {

                        System.out.println("Adding file: " + files[i].getName());

                        FileInputStream fis = new FileInputStream(files[i]);

                        // begin writing a new ZIP entry, positions the stream to the start of the entry data
                        zos.putNextEntry(new ZipEntry(files[i].getName()));

                        int length;

                        while ((length = fis.read(buffer)) > 0) {
                            zos.write(buffer, 0, length);
                        }

                    zos.closeEntry();

                        // close the InputStream
                        fis.close();
                    }


    // close the ZipOutputStream
                    zos.close();

                }
                catch (IOException ioe) {
                    System.out.println("Error creating zip file" + ioe);
                }
                return zipFile;

            }