java 多应用打包

package com.cmsz.resource.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
*
* @author pengming01
*
*/
public class FilesManager {
/**
* 创建文件夹
*
* @param path
*            创建文件夹的路径
* @return
*/
public File createFolder(String path) {
File dirFile = null;
try {
dirFile = new File(path);
if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
dirFile.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
return dirFile;
}

/**
* 文件夹修改
* @param filePath   D:\\upload\\自动化需求详细设计11.xls
* @param newFolderName   D:\\upload\\自动化需求详细设计.xls
* @return
*/
public Map<String,String> reNameFolder(String filePath,String newFolderName){
System.out.println("FilesManager--46--------"+filePath);
System.out.println("FilesManager--47--------"+newFolderName);
Map<String,String> folderMap = new HashMap<String,String>();
File file = new File(newFolderName);
new File(filePath).renameTo(file);
folderMap.put(file.getAbsolutePath(), file.getName());
return folderMap;
}

/**
* 文件夹修改
* @param filePath   D:\\upload\\自动化需求详细设计11.xls
* @param newFolderName   D:\\upload\\自动化需求详细设计.xls
* @return
*/
public Map<String,String> revieweNameFolder(String filePath,String newFolderName){
System.out.println("FilesManager--46--------"+filePath);
System.out.println("FilesManager--47--------"+newFolderName);
Map<String,String> folderMap = new HashMap<String,String>();
File file = new File(newFolderName);
new File(filePath).renameTo(file);
folderMap.put(file.getAbsolutePath(), file.getName());
return folderMap;
}

//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
   public static boolean delAllFile(String path) {
       boolean flag = false;
       File file = new File(path);
       if (!file.exists()) {
         return flag;
       }
       if (!file.isDirectory()) {
         return flag;
       }
       String[] tempList = file.list();
       File temp = null;
       for (int i = 0; i < tempList.length; i++) {
          if (path.endsWith(File.separator)) {
             temp = new File(path + tempList[i]);
          } else {
              temp = new File(path + File.separator + tempList[i]);
          }
          if (temp.isFile()) {
             temp.delete();
          }
          if (temp.isDirectory()) {
             delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
             delFolder(path + "/" + tempList[i]);//再删除空文件夹
             flag = true;
          }
       }
       return flag;
     }

//删除文件夹
//param folderPath 文件夹完整绝对路径

   public static void delFolder(String folderPath) {
   try {
  
   String[] mutilPath = folderPath.split("☆");
   if(mutilPath.length == 1){
   System.out.println(folderPath);
     delAllFile(folderPath); //删除文件里面所有内容
      String filePath = folderPath;
      filePath = filePath.toString();
      java.io.File myFilePath = new java.io.File(filePath);
      myFilePath.delete(); //删除空文件夹
   }
   else{
   for (int i = 0; i < mutilPath.length; i++) {
   System.out.println("-----"+mutilPath[i]);
   delAllFile(mutilPath[i]); //删除文件里面所有内容
   java.io.File myFilePath = new java.io.File(mutilPath[i]);
   myFilePath.delete(); //删除空文件夹
   }
   }
     
   } catch (Exception e) {
     e.printStackTrace();
   }
}
 
  
/**
* 根据目录打包
*
* @param SourcePath
*            打包目录
* @param zipFilePath
*            目标压缩文件路径
*/
public String zip(String zipFilePath, String inputFolderName)
throws Exception {
String zipFileName = zipFilePath; // 打包后文件名字
File zipFile = new File(inputFolderName);
FileOutputStream fileOut = new FileOutputStream(zipFileName);
ZipOutputStream out = new ZipOutputStream(fileOut);
zip(out, zipFile, "");
out.close();
fileOut.close();
return zipFilePath;
}

public void zip(ZipOutputStream out, File inputFolder, String base)
throws Exception {
if (inputFolder.isDirectory()) {

File[] fl = inputFolder.listFiles();
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(inputFolder);
int b;
// System.out.println(base);
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}

/**
* 根据目录打包
*
* @param SourcePath
*            打包目录
* @param zipFilePath
*            目标压缩文件路径
*/
public void folderZip(String SourcePath, String zipFilePath) {
File zipFile = new File(SourcePath);
int len = zipFile.listFiles().length;
String[] filenames = new String[len];
byte[] buf = new byte[1024];
try {
File[] files = zipFile.listFiles();
for (int i = 0; i < len; i++) {
filenames[i] = zipFile.getPath() + File.separator
+ files[i].getName();
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFilePath));

for (int i = 0; i < filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);
out.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
out.closeEntry();
in.close();
}
out.close();
} catch (IOException e) {
System.out.println(e);
}
}

public static void zipFile(String baseDirName, String[] fileNames,
String targetFileName) throws IOException {
/**
* 由这个 "压缩的根目录" 文件名路径得到一个 File 对象 并判断这个 File 对象表示的文件是否存在! 是否是一个文件夹!.....
*/
File baseDir = new File(baseDirName);
if (!baseDir.exists() || (!baseDir.isDirectory())) {
System.out.println("压缩失败! 根目录不存在: " + baseDirName);
return;
}
// 得到这个 "压缩的根目录" 的路径.........
String baseDirPath = baseDir.getAbsolutePath();
/**
* 由这个 "目标 ZIP 文件" 文件名得到一个 压缩对象 ZipOutputStream
*/
File targetFile = new File(targetFileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
targetFile));
// "*" 表示压缩包括根目录 baseDirName 在内的全部文件 到 targetFileName文件下
if (fileNames.equals("*")) {
FilesManager.dirToZip(baseDirPath, baseDir, out);
} else {
File[] files = new File[fileNames.length];
for (int i = 0; i < files.length; i++) {
// 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
files[i] = new File(baseDir, fileNames[i]);
}
if (files[0].isFile()) {
// 调用本类的一个静态方法 压缩一个文件
// CompressUtil.fileToZip(baseDirPath, file, out);
FilesManager.filesToZip(baseDirPath, files, out);
}

}
out.close();
System.out.println("压缩成功! 目标文件名为: " + targetFileName);
}

/**
  *
  * *************************************************多个文件目录压缩到Zip 输出流
  * *************************************************
  */
public static void filesToZip(String baseDirPath, File[] files,
   ZipOutputStream out) throws IOException {
   // 遍历所有的文件 一个一个地压缩
   for (int i = 0; i < files.length; i++) {
    File file = files[i];
    if (file.isFile()) {
     // 调用本类的一个静态方法 压缩一个文件
    FilesManager.fileToZip(baseDirPath, file, out);
    } else {
     /*
      * 这是一个文件夹 所以要再次得到它下面的所有的文件
      * 这里是自己调用自己..............递归..........
      */
     FilesManager.dirToZip(baseDirPath, file, out);
    }
   }
}
public static void dirToZip(String baseDirPath, File dir,
ZipOutputStream out) throws IOException {
// 得到一个文件列表 (本目录下的所有文件对象集合)
File[] files = dir.listFiles();
/**
* 要是这个文件集合数组的长度为 0 , 也就证明了这是一个空的文件夹
*
* 虽然没有再循环遍历它的必要,但是也要把这个空文件夹也压缩到目标文件中去
*/
if (files.length == 0) {
// 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例
/*String zipFileName = getEntryName(baseDirPath, dir);
System.out.println("zipFileName--------------------------"+baseDirPath+zipFileName);
ZipEntry entry = new ZipEntry(baseDirPath+zipFileName);
//System.out.println("entry.getName()-============="+entry.getName());
out.putNextEntry(entry);
out.closeEntry();*/
} else {
// 遍历所有的文件 一个一个地压缩
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isFile()) {
System.out.println("direToZip method================="+baseDirPath);
System.out.println("direToZip method================="+file.getAbsolutePath());
// 调用本类的一个静态方法 压缩一个文件
FilesManager.fileToZip(baseDirPath, file, out);
} else {
/*
* 这是一个文件夹 所以要再次得到它下面的所有的文件
* 这里是自己调用自己..............递归..........
*/
FilesManager.dirToZip(baseDirPath, file, out);
}
}
}
}

/**
*
* ************************************************* 获取待压缩文件在 ZIP 文件中的 entry
* 的名字! 即相对于根目录的相对路径名 *************************************************
*
*/
public static String getEntryName(String baseDirPath, File file) {
/**
* 改变 baseDirPath 的形式 把 "C:/temp" 变成 "C:/temp/"
*/
if (!baseDirPath.endsWith(File.separator)) {
baseDirPath += File.separator;
System.out.println(baseDirPath);
}
String filePath = file.getAbsolutePath();
/**
* 测试此抽象路径名表示的文件是否是一个目录。 要是这个文件对象是一个目录 则也要变成 后面带 "/"
*
* 这个文件对象类似于 "C:/temp/人体写真/1.jpg"
*
* 要是这个文件是一个文件夹 则也要变成 后面带 "/" 因为你要是不这样做,它也会被压缩到目标文件中 但是却不能正解显示
* 也就是说操作系统不能正确识别它的文件类型(是文件还是文件夹)
*/
if (file.isDirectory()) {
filePath += "\\";
}
int index = filePath.indexOf(baseDirPath);
return filePath.substring(index + baseDirPath.length());
}

public static void fileToZip(String baseDirPath, File file,
ZipOutputStream out) throws IOException {
//
/*FileInputStream in = null;
ZipEntry entry = null;
// 创建复制缓冲区 1024*4 = 4K
byte[] buffer = new byte[1024 * 4];
int bytes_read = 0;
out.setEncoding("GBK");
if (file.isFile()) {
in = new FileInputStream(file);
// 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例
String zipFileName = getEntryName(baseDirPath, file);
System.out.println("baseDirPath========="+baseDirPath);
System.out.println("===================="+zipFileName);
entry = new ZipEntry(zipFileName);
// "压缩文件" 对象加入 "要压缩的文件" 对象
out.putNextEntry(entry);
// 现在是把 "要压缩的文件" 对象中的内容写入到 "压缩文件" 对象
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
in.close();
System.out.println("添加文件" + file.getAbsolutePath()
+ "被添加到 ZIP 文件中!");
}*/
try{


byte[] buff = new byte[2048];
int bytesRead = -1;
System.out.println("returnpathXXXXXXXXXX==========="+new StringBuffer(baseDirPath).append("\\").toString());
ZipEntry entry = new ZipEntry(new StringBuffer(baseDirPath).append("\\").toString());
out.putNextEntry(entry);
System.out.println("文件将要被打包中=============="+file.getAbsolutePath());
InputStream in = new BufferedInputStream(new FileInputStream(file));
while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
out.write(buff, 0, bytesRead);
}
in.close();
out.flush();
}catch(Exception e){}
}

/**
* 功能:压缩成zip
*
* @param zipFilep
*            压缩后的zip文件名
* @param path
*            压缩路径
* @throws java.lang.Exception
*/
public void zip(ZipOutputStream out, String path) {
System.out.println("压缩文件开始.....................");

try {
write(out, path, "");
System.out.println("压缩文件结束!");
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 功能:写压缩流
*
* @param out
*            压缩输出流
* @param path
*            压缩路径
* @param base
*            压缩式的基础目录
* @throws java.lang.Exception
*//*

public void write(ZipOutputStream out, String path, String base)
throws Exception {
System.out.println("path------------------"+path);
File file = new File(path);
if (file.isDirectory()) {// 文件夹,递归
base = base.length() == 0 ? "" : base + File.separator;
File[] tempFiles = file.listFiles();
for (int i = 0; i < tempFiles.length; i++) {
write(out, tempFiles[i].getPath(),
base + tempFiles[i].getName());
}
} else {// 文件,压缩
byte[] buff = new byte[2048];
int bytesRead = -1;
ZipEntry entry = new ZipEntry(base);
out.putNextEntry(entry);
InputStream in = new BufferedInputStream(new FileInputStream(file));
while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
out.write(buff, 0, bytesRead);
}
in.close();
out.flush();
}
}
*/
/**
* 功能:压缩成zip
*
* @param zipFilep
*            压缩后的zip文件名
* @param path
*            压缩路径
* @throws java.lang.Exception
*/
public static void zip(ZipOutputStream out, String[] path) {
System.out.println("压缩文件开始.....................");

try {
for (int i = 0; i < path.length; i++) {
System.out.println(" path[i]======================="+path[i]);
System.out.println("getENtryName====================="+getEntryName("D:\\baseReview",new File(path[i])));
write(out, path[i], getEntryName("D:\\baseReview",new File(path[i])));
}
System.out.println("压缩文件结束!");
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 功能:写压缩流
*
* @param out
*            压缩输出流
* @param path
*            压缩路径
* @param base
*            压缩式的基础目录
* @throws java.lang.Exception
*/

public static void write(ZipOutputStream out, String path, String base)
throws Exception {
File file = new File(path);
out.setEncoding("GBK");
if (file.isDirectory()) {// 文件夹,递归
base = base.length() == 0 ? "" : base + File.separator;
File[] tempFiles = file.listFiles();
if (tempFiles.length == 0) {
// 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例
ZipEntry entry = new ZipEntry(base);
out.putNextEntry(entry);
out.closeEntry();
} else {
for (int i = 0; i < tempFiles.length; i++) {
write(out, tempFiles[i].getPath(),
base + tempFiles[i].getName());
}
}
} else {// 文件,压缩
byte[] buff = new byte[2048];
int bytesRead = -1;
ZipEntry entry = new ZipEntry(base);
out.putNextEntry(entry);
InputStream in = new BufferedInputStream(new FileInputStream(file));
while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
out.write(buff, 0, bytesRead);
}
in.close();
out.flush();
}
}
/*public static void main(String[] args) {

File[] fileList = new File[3];
File file1 = new File("D:\\baseReview\\新业务集成测试系统\\业务集成测试跟踪及注意事项.xlsx");
File file2 = new File("D:\\baseReview\\新业务集成测试系统\\测试2");
File file3 = new File("D:\\baseReview\\新业务集成测试系统\\资源共享验收测试\\资源共享验收测试\\测试用例_自动化网厅账单查询_20130124.xlsx");
File zipFile = new File("D:\\测试.zip");
fileList[1]=file2;
fileList[2]=file3;
fileList[0]=file1;
ZipOutputStream zipOut;
try {
zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
try {
FilesManager.filesToZip("D:\\baseReview", fileList, zipOut);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// fileList.add(file2);
//fileList.add(file3);

try {
String[] fileList = new String[5];
File file = new File("D:\\baseReview\\彭明本机文件\\2013-01-14 11-36-00.xls");
File file1 = new File("D:\\baseReview\\彭明本机文件\\2013-03-04 14-24-54.xls");
File file2 = new File("D:\\baseReview\\彭明本机文件\\本机目录1\\ant.jar");
File file3 = new File("D:\\baseReview\\彭明本机文件\\本机目录1\\测试学习计划.doc");
File file4 = new File("D:\\baseReview\\彭明本机文件\\本机目录1\\子目录");

File zipFile = new File("D:\\测试.zip");
fileList[0]=file.getAbsolutePath();
fileList[1]=file1.getAbsolutePath();
fileList[2]=file2.getAbsolutePath();
fileList[3]=file3.getAbsolutePath();
fileList[4]= file4.getAbsolutePath();
//System.out.println(file4.getAbsolutePath());
ZipOutputStream zipOut;
try {
zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
try {

FilesManager.zip(zipOut,fileList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}*/

}

猜你喜欢

转载自fkueje001.iteye.com/blog/1838876
今日推荐