我想压缩多个目录。这意味着我有1个内部目录和1个父目录。现在我想压缩父目录。
我使用以下代码:
我的文件路径:
/data/data/com/app/1430159400000/32640/Images/capture_Image_20150427_115541.png"
/data/data/com/app/1430159400000/32640/Images/capture_Image_20150427_115542.png"
/data/data/com/app/1430159400000/32640/Images/ChildImages/capture_Image_20150427_115543.png"
/data/data/com/app/1430159400000/32640/Images/ChildImages/capture_Image_20150427_115544.png"
/data/data/com/app/1430159400000/32640/Images/capture_Image_20150427_115545.png"
/data/data/com/app/1430159400000/32640/Images/capture_Image_20150427_115546.png"
从目录中获取文件: -
public void getListFilesForCreatingZip(File parentDir) {
String[] filesPath = null;
File[] files = parentDir.listFiles();
filesPath = new String[(int) parentDir.length()];
int index = 0;
int index1=0;
for (File file : files) {
if (file.isDirectory()) {
if(file.getName().equals("ChildImages"))
{
File[] files1 = file.listFiles();
for(File ss:files1)
{
filesPath[index]=ss.getPath();
index++;
}
}
} else {
filesPath[index] = file.getPath();
}
index++;
}
zip(filesPath, "PathName";
}
要Zip文件: -
public void zip(String[] _files, String zipFileName) {
try {
BufferedInputStream origin = null;
/*File root = Application.getInstance().getDir("bol", Context.MODE_PRIVATE);
File customDir = new File(root + File.separator + File.separator + PreferenceManagerForBol.getInstance().getBolSelectedDate() + File.separator + PreferenceManagerForBol.getInstance().getBolOrderNumber());
if (customDir.exists() == false) {
customDir.mkdirs();
} */
File file = new File(BolDetailsHandler.getInstance().createBasePath(), zipFileName + ".zip");
FileOutputStream dest = new FileOutputStream(file);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; i++) {
if(!_files[i].contains(".zip"))
{
Logger.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
当我使用以下代码时,我在zip()方法中面临空指针异常。当zip()方法尝试读取子路径并再次尝试读取它显示空指针异常的父路径时。
请让我解决这个问题。
答案 0 :(得分:1)
index++;
。你有两个。在filesPath[index] = file.getPath();
之后直接放置第二个像第一个。
但你的String数组filesPath = new String [(int)parentDir.length()];以这种方式不会有合适的尺寸。子目录的文件没有空间。
你可以更好地使用<String> ArrayList
,因为你可以随意添加,而不必正确知道会有多少。