您的位置:首页 > Web前端

文件遍历

2007-12-06 14:50 183 查看
public String zipFiles(String[] fnames,HttpServletRequest request) {
        ArrayList fileNames = new ArrayList();
        ArrayList files = new ArrayList(); // 存放文件对象
        String filePath = "/download/";
        String serverPath = request.getRealPath("/");
        String getfn = getFileName("zip");
        StringBuffer sbf = new StringBuffer();
        sbf.append(serverPath);
        sbf.append(filePath);
        sbf.append(getfn);
        sbf.append(".rar");
        String fullPaht = serverPath+filePath+getfn+".zip";
        try {
            FileOutputStream fileOut = new FileOutputStream(fullPaht);
            ZipOutputStream outputStream = new ZipOutputStream(fileOut);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
           
            File rootFile = null;
            for (int s = 0; s < fnames.length; s++) {
                rootFile = new File(fnames[s]);
                listFile(rootFile, fileNames, files);
            }
           
            for (int loop = 0; loop < files.size(); loop++) {
                FileInputStream fileIn = new FileInputStream((File) files.get(loop));               
                BufferedInputStream bisOne = new BufferedInputStream(fileIn);
               
                outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
               
                int value = -1;
                while ((value = bisOne.read()) != -1) {
                    bos.write(value);
                }
                bos.flush();
                bisOne.close();
               
//                byte[] buffer = new byte[1024];
//                while (fileIn.read(buffer) != -1) {
//                    outputStream.write(buffer);
//                }
//                fileIn.close();
//                outputStream.closeEntry();
            }

            outputStream.close();
//            fileOut.close();
           
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return fullPaht;
    }

  
    static void listFile(File parentFile, List nameList, List fileList) {
        if (parentFile.isDirectory()) {
            File[] files = parentFile.listFiles();
            for (int loop = 0; loop < files.length; loop++) {
                listFile(files[loop], nameList, fileList);
            }
        } else {
            fileList.add(parentFile);
            nameList.add(parentFile.getName());
        }
    }
    public static String s_cl(String s){
        s = s.trim();
        if(s==null || s.equals("") || s.equals("null")){
            s = "";
        }
        return s;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息