PDA

View Full Version : zip کردن محتویات یه پوشه!



Amin-rz
چهارشنبه 12 شهریور 1393, 18:03 عصر
من از این کد برای zip کردن محتویات یه پوشه استفاده می کنم.ولی خود پوشه رو zip می کنه(البته محتویاتشم داخلش هست).
چه تغییری باید بدم که محتویات پوشه AndroBook رو بریزه تو file.zip نه خودشو؟


final File root = android.os.Environment.getExternalStorageDirectory ();
zipFileAtPath(root.getAbsolutePath()+ "/AndroBook", root.getAbsolutePath()+"/file.zip");


public boolean zipFileAtPath(String sourcePath, String toLocation) {
// ArrayList<String> contentList = new ArrayList<String>();
final int BUFFER = 2048;


File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}





private void zipSubFolder(ZipOutputStream out, File folder,int basePathLength) throws IOException {

final int BUFFER = 2048;

File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
Log.i("ZIP SUBFOLDER", "Relative Path : " + relativePath);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}




public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}