How to save only zip files and remove other folders using java? -
here have folder(books)in have 3 sub folders named:sub1, sub2, sub3 , sub1 have 2 files, sub2 have 3 files, sub3 have 4 files. , sub1.zip,sub2.zip , sub3.zip. want keep zip files , delete sub1, sub2, sub3 folders of books. code i'm able delete inside files of sub1 folder, sub2, sub3 folders becoming empty, how can delete sub1,sub2 , sub3 folders.
public void savezipfiles(file destwithouaudio) throws ioexception { file[] listoffiles = destwithouaudio.listfiles(); (file listoffile : listoffiles) { if (listoffile.getname().endswith(".zip")) { } else { file folderinside = new file(listoffile.getabsolutepath()); file[] listoffilesinside = folderinside.listfiles(); (file listoffilesinside1 : listoffilesinside) { file deletefolder = new file(listoffilesinside1.getabsolutepath()); //system.out.println(""+listoffilesinside[j]); recursivedelete(deletefolder); } } } }
recursivedelete method code is:
public static void recursivedelete(file file) throws ioexception { if (file.isdirectory()) { if (file.list().length == 0) { file.delete(); system.out.println("directory deleted : " + file.getabsolutepath()); } else { string files[] = file.list(); (string temp : files) { file filedelete = new file(file, temp); recursivedelete(filedelete); } if (file.list().length == 0) { file.delete(); system.out.println("directory deleted : " + file.getabsolutepath()); } } } else { file.delete(); system.out.println("file deleted : " + file.getabsolutepath()); } }
after deleting files sub1,sub2,sub3 foldersii need delete sub1,sub2,sub3 folders.
where change code?
public void deletedir(file dir) { if (dir.isdirectory()) { string[] children = dir.list(); (int = 0; < children.length; i++) { boolean success = deletedir(new file(dir, children[i])); if (!success) { return false; } } } return dir.delete(); // directory empty , can deleted. }
then, using
public void savezipfiles(file destwithouaudio) { file[] deletion = destwithouaudio.listfiles(new filenamefilter() { @override public boolean accept(file dir, string name) { return !name.endswith(".zip"); } }); (file todelete : deletion) { deletedir(todelete); } }
(using deleting folder java folder deletion)
Comments
Post a Comment