JAVA壓縮文件夾包括裏面的文件,可以設置壓縮後的目錄結構

package test.downloadzip;


/* 
 * 在進行壓縮流操作時建議使用開源的類庫org.apache.tools.zip.*, 
 * 不要用java.util.zip.*類庫,這個在實現上沒有前面那個做的完善。 
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipDemo {


public static TreeSet<String> ts = new TreeSet<String>();


public static void main(String[] args) throws IOException {
// 需要壓縮的目錄
File sFolder = new File("D:\\leo\\file\\pic");

// 壓縮之後的目錄,如果是網絡下載情況可以將流寫入response就好了
File zipFolder = new File("d:\\zipDown\\test.zip");


ZipFolderMethod(sFolder, zipFolder);


System.out.println("導出成功");


}


public static void ZipFolderMethod(File sFoder, File zipFolder) throws IOException {
// TODO Auto-generated method stub


ZipOutputStream zipoutFolder = new ZipOutputStream(new FileOutputStream(zipFolder));


InputStream in = null;


// zipoutFolder.setEncoding("GBK"); //爲解決註釋亂碼
zipoutFolder.setComment("文件夾的壓縮");


// 列出所有文件的路徑,保存到集合中,在ListAllDirectory(sFoder)方法中用到遞歸
TreeSet<String> pathTreeSet = ListAllDirectory(sFoder);


String[] pathStr = pathTreeSet.toString().substring(1, pathTreeSet.toString().length() - 1).split(",");


for (int i = 0; i < pathStr.length; i++) {
String filePath = pathStr[i].trim();
StringBuffer pathURL = new StringBuffer();
String[] tempStr = filePath.split("\\\\"); // 這個地方需要注意,在Java中需要“\\\\”表示“\”字符串。


// 這裏的變量j是從第幾層開始打壓縮包
for (int j = 6; j < tempStr.length - 1; j++) {
pathURL.append(tempStr[j] + File.separator);
}
String path = pathURL.append(tempStr[tempStr.length - 1]).toString();


in = new FileInputStream(new File(filePath));


zipoutFolder.putNextEntry(new ZipEntry(path));


int temp = 0;
while ((temp = in.read()) != -1) {
zipoutFolder.write(temp);
}


in.close();
}
zipoutFolder.close();
}


public static TreeSet<String> ListAllDirectory(File sFolder) {
if (sFolder != null) {
if (sFolder.isDirectory()) {
File f[] = sFolder.listFiles();
if (f != null) {
for (int i = 0; i < f.length; i++) {
ListAllDirectory(f[i]);
}
}
} else {
ts.add(sFolder.toString());
}
}
return ts;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章