2

我有这个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方法中完成ZipFilefilename.indexOf(".")我知道这是返回 null ,因为我尝试使用而不是检测文件是文件夹还是文件,isDirectory()并且isFile()因为它们不起作用。但我希望我对此有一个解释。

谢谢你的帮助!

4

4 回答 4

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

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

于 2013-08-22T10:52:59.807 回答
0

可能是路径有问题?

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

您正在将反斜杠与斜杠混合...

于 2013-08-22T09:37:15.617 回答
0

我测试了你的代码块

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

使用本地文件夹,它运行良好。我认为您正在通过无效路径。这可能是isFileisDirectory方法行为异常的原因。尝试使用File API在generateFileList方法的开头添加验证语句:

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

这应该有效。

于 2013-08-22T10:11:56.087 回答
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;

            }
于 2014-10-31T06:28:44.010 回答