Help me Friends - How to Delete a Folder and its contents in java

Hi Friends
I want to delete a folder and its contents by passing the folderpath.
Can any one help me in this..
Thanks in Advance
Regards
Krishna

* Delete a directory including all of its content.
* @param directory Directory path to delete.
public static void deleteDirectory(String directory) {
if (directory != null) {
File file = new File(directory);
if (file.exists() && file.isDirectory()) {
//1. delete content of directory:
File[] files = file.listFiles();
int count = files.length;
for (int i = 0; i < count; i++) { //for each file:
File f = files;
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteDirectory(f.getAbsolutePath());
}//next file
file.delete(); //finally delete (empty) input directory
}//else: input directory does not exist or is not a directory
}//else: no input value
}//deleteDirectory()

Similar Messages

  • How to extract a folder (and its contents) from inside a zip file?

    There is a zip file which contains a folder inside it. The folder itself contains a few files. I would need to know how to extract the folder (with its contents) from inside a zip file.
    I have found a few unzipping code samples which show how to handle a folder inside a zip file. An example is shown below:
    public static void extract(String workingDirectory, byte[] zipFile)
    throws Exception {
    ByteArrayInputStream byteStream = new ByteArrayInputStream(zipFile);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipInputStream zipStream = new ZipInputStream(byteStream);
    ZipEntry zipEntry = null;
    String nameZipEntry = null;
    byte[] contentZiphttp://forum.java.sun.com/post!default.jspa?forumID=31#
    Click for code tagsEntry = null;
    boolean isDirectory = false;
    int indexFileSeparator = -1;
    String directory = null;
    String fileName =  null;
    while ( (zipEntry = zipStream.getNextEntry()) != null )
                nameZipEntry = workingDirectory + File.separator + zipEntry.getName();
                isDirectory = zipEntry.isDirectory();
                if (isDirectory) {
    File file = new File(nameZipEntry);
    file.mkdirs();
                else
                    // read zipEntry
                    byte[] buf = new byte[1024];
                    int c = 0;
                    while ( (c = zipStream.read(buf)) != -1)
                        out.write(buf, 0, c);
                    indexFileSeparator = nameZipEntry.lastIndexOf(File.separator);
                    directory = nameZipEntry.substring(0, indexFileSeparator);
                    fileName =  nameZipEntry.substring(indexFileSeparator+1,nameZipEntry.length());
                    FileSystemTools.createFile(directory, fileName, out);
                    out.reset();
                    zipStream.closeEntry();
            zipStream.close();
            byteStream.close();
    }The code sample which deals with the part where the zipEntry is a directory creates a directory with the same path and name. (highlighted in bold)
    Another similar variation is:
    File file = new File(dirDestiny.getAbsolutePath() + File.separator + zipEntry.getName() );
    if(zipEntry.isDirectory())
          file.mkdirs();When the code creates a directory for the folder, does it unzip the contents inside the folder as well?
    If not, how do I extract the files inside the folder?

    Have you already tried to see if the sample code you downloaded works or not? Maybe if you try out the code yourself you can see if it extracts files from a directory within a zip file?
    I like to use pkzip. It is a command line compression/uncompression tool that can be used from a batch file. If you assignment involves unzipping large amount of zip files on a regular basis, I recommend taking a look at pkzip.

  • Is it possible to recover a deleted folder and its contents as opposed to an individual file?

    When I turned on my computer today, a folder located on my desktop is no longer there.  Astounded I could have accidentally deleted it, the folder having been trashed is the only illogical logical possibility I can think of - and is a first for me in my 30 years of Mac use.  My father is in the process of dying and the folder contains all the information coming to me on the subject.  The last backup of this folder is about a week old and much has been added since for which I've no record.
    Not having a master document or table of contents listing what was in the folder leaving me unable to search for and recover individual files/documents by name, my question is this:  Is it possible to recover a "FOLDER", and its contents after that folder has been moved from the desktop to the trash, the trash emptied, and the computer having been shut down?
    If anyone has any ideas of how to recover anything about what items that folder contained, I'd really appreciate whatever thoughts you might have.
    Thanks in advance -
    The computer this folder is missing from is a early 2008 MacPro, running 10.7.5.

    I'm not sure what you can do beyond trying to restrict the types of files you search for. These apps normally have ways to select the file types or to add example files. That allows them to carve out only those types, but you still may end up with GB's of data, especially if the types are somewhat generic. I don't know of any tools that can undo changes to the disk catalog over time.
    I guess you could also search for specific text if you know that these files contained something that is 'almost unique'. Spotlight can do that, or grep, egrep are command line tools that may help ask if you want to go that route, they may help you gather lists to move files around to whittle them down.
    Sorry I can't think of a way around this it's a difficult task at a difficult time. Good luck with it, ask if you think we could help.
    I do wonder if Apples 'Versions' could help?
    OS X Lion: About Auto Save and Versions - Apple Support
    @Tony T1, do you know how to restore files from that system? I think it is part of Time Machine, but the copies are saved locally.
    It is not entirely clear how it works (at least from my memory of Lion) with regards to how you could get files back in this situation. The database should be at the base of the disk in a hidden folder ".DocumentRevisions-V100", but I don't think you can just pull files out of there. Personally I'd consider making a full disk backup before you attempt to restore files. Then you could try the 'Enter Time Machine' UI to see if it can browse back to the older Desktop.

  • HT201301 How do I import a garageband project folder (and its contents) into itunes?

    How do I import a garageband project folder (and its contents) into itunes so I can transfer it to my ipad?
    I am a guitar teacher and I want to use garageband for the ipad as a teaching tool for my students.  The goal is for my students and myself to share garageband project files so that both the teacher and the student can have the full project...or even add to it.
    Here's what I need help with...
    My student has created a song in garageband that has 4 tracks.  They sync their song to itunes so they can see the project folder for that song in the document window for garageband under the "apps" tab in itunes.  They click "save to" and save the project folder to dropbox. 
    I want to be able to import the project folder for that song from dropbox into itunes so that I can copy it to my ipad and have full access to my student's song.
    I appreciate any help!  Thanks!
    Pat
    [email protected]

    hi Pat,
    what you can do is add that folder to garageband directory using ifunbox. here is the step:
    - Open your ifunbox then go to "user Applications" on your left panel, then select garageband folder. You will see a folder as below:-
    "Documents"
    "Library"
    "MobileGarageBand.app"
    "tmp"
    "itunesartwork"
    "itunesmetada.plist"
    copy the folder you like to put into your ipad by copy it into "Documents" folder. and then quit the ifunbox and restart your itunes again and sync your ipad again and check if you can see the folder on your file sharing under apps tab. Wish you good luck.

  • Mac OS 10.5 /  I deleted the " Private" folder ... and emptied the trash. So the folder and its contents no longer exists on my computer at all !!!  I do have the OS dvd that i purchased years ago...  But my computer will not start from it on its own. My

    Mac OS 10.5 /
    I deleted the " Private" folder ... and emptied the trash. So the folder and its contents no longer exists on my computer at all !!!
    I do have the OS 10.5 dvd that i purchased years ago...
    But my computer will not start from it on its own.
    My question is what is the open source or terminal language code used to tell my mac to look in the DVD rom drive for startup info?  I know that im not the only person in this world who has deleted the "PRIVATE" folder and emptied the trash so it no longer exists on their machine...
    That said theres gotta be a common fix for a Power PC G4 that has the OS X dvd in the rom drive but wont look to it to reinstall the vital contents of the PRIVATE folder.
    Once again there is not a copy of this file or its contents in the recycle bin...
    Also rebooting the machine , pressing and holding the letter C does not prompt the machine to look to the dvd rom drive.
    I was reinstalling pro tools and figured I would make some room by cleaning my computers HD...
    Lol It was a bad choice to delete this file ...
    Thanks guys

    Okay sorry it took forever to respond... But for a while there I gave up on this computer!!!!
    Money's been tight lately , so taking it in to a professional was not yet an option... though I did consider it eventhough.
    Anyway long story short im glad I didnt spend any money because I already had all the tools necessary to fix this issue but was going about it in the wrong way. Okay so here is my scenario and the breakdown... Though this may not fix the issue for everyone :( which *****... But I know we all will have different circumstances.
    Anyway here we go...
    Okay so first things first....  Years ago I purchased the OS 10.5.1 disk ... So that has always been in my possession!!!!
    I realize that some may not have a disk to reflash your OS to your hard drive... but if you do your in luck.
    2ndly ... I had an external harddrive with all of my itunes downloaded music so it was more than okay with me to delete my primary HD because all the important stuff could either be copied over or repathed to be located.
    -------If you dont want to read through the whole story the fix is summed up in the bottom section-------
    Okay so now the SOLUTION!!!!
    By trial and error , and pure boredom I opened up my computer to clean the inside...
    AND
    "Disconnected the primary HD"
    and just because ....... REBOOTED my computer. Just to see what it would do.
    Upon restart and though it looked like it would repeat its usual cycle...
    About 1 minute in to that process my computer froze for about 2 seconds and flashed to the OS installation screen.
    Mind you I havent seen this screen yet... Probably hasnt been since I installed the OS years ago.
    After a bit of trial and error...
    I decided to tell my computer to startup from the OS 10.5 disk located in my dvd rom drive and restarted once again...
    this setting is under
    Utilities / startup disk
    After a little more trial and error ... I realized that I could reconnect the primary HD , restart the machine and return to the OS installation menu.
    So upon this discovery
    I went to the Disk Utility located under Utilities
    Highlighted my primary HD located in the left hand column
    Once highlighted ...
    In the heading section on the right I selected the option
    Erase
    in which I erased My current OS on my primary HD ...
    I used the first option in the list under security... Because it seemed like the least invasive and would take the least amount of time to see if this process would actually work.
    I FORGOT to add something... 
    Another reason why I deleted my primary HD!!!!!
    I forgot to say that it WOULD NOT!!!!! Show up in the STARTUP list as an option...Even After multiple reboots....
    But like clockwork... Once I deleted its name IT SHOWED UP as an option!!!!
    So back to the next step...
    I returned to the STARTUP option under utilities ... And was then able to see MY primary HD now as a startup option...
    But ofcourse it had no name because it we previously erased it.
    So when Clicking my newly erased HD ... I was almost immediately prompted to REINSTALL the OS ...
    Which said it would take about 57 minutes ... But I believe was alot less...
    My issue was resolved ... My computer then stated the install was SUCCESSFUL!!!!!!! :))))))))))) lol ;)
    It was like I was setting up for the first time ;) asking for my registration info...
    The dilemma of deleting the private folder and emptying the trash is finally over resolved. Done ... and no extra money spent!!!!!!!!! 
    Its really crazy that the information for such a simple thing is not readily available. Especially being such a simple fix.
    I know im not the only person who's had this issue , because i've seen numerous posts with similar wording.
    I also know I wont be the last person to have this issue... So I hope this synopsis makes sense.
    -------One more time the fix------
    *Insert your OS dvd into your dvd rom drive.
    *Unplug your primary HD or corrupted startup disk
    *Reboot your machine...
    Upon restart your primary HD will not be recognized...
    * you will then be prompted to select your language.
    Once selected
    *Click Utilities/startup... Highlight the the selection that refers to the OS dvd located in the dvd rom drive.
    * Click restart...
    !!!!!!!!!!Be sure to reconnect your Primary HD Before your computer restarts and you hear the chime!!!!!!!!
    If you do not replug your HD before the chime it will not be recognized.
    In that case restart again.
    Upon restart once again
    *Choose your language...
    *Click Utilities / disk utility
    In the left column select and
    *Highlight your HD ...
    Then towards the top portion / center of the page
    *Click the heading Erase
    Then on the page toward the bottom
    *Click security options
    This will then provide erase options.
    I USED THE FIRST OPTION
    "Dont erase data"...
    *click OK
    * click erase...
    Once erased which should take a few seconds
    *Cancel the disk utility...
    * Click Utilities / startup
    And your newly erased HD should now appear in the list.
    * Select your drive from the list by highlighting
    It should no longer have a name.
    *Once selected, you will then be prompted to restart and install the OS to your newly erased HD...
    Thats it!!!!
    Once everything reinstalls re-add your personal info or registration info and you are up and running.
    Goodluck ;)

  • Deleting a directory and its content

    Hi, I'm trying to delete a series of directories like this batch file does
    @echo Removing "%CD%\a"
    @rmdir /s /q "%CD%\a"
    @echo Removing "%CD%\b"
    @rmdir /s /q "%CD%\b"
    @echo Removing "%CD%\c"
    @rmdir /s /q "%CD%\c"looking at the api i found that it doesn't seem to have the option to delete a dir and its content, should i use a function like the one in thread:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=188034
    or would it be better to call the batch script with Runtime.exec()? The system is windows only so i don''t need to have compatibility with *nix shells ect.
    What do you think?

    Try this
    // CLASS:    FileUtil
    // FUNCTION: An extension of File which allows various file manipulations
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class FileUtil
        extends File {
       public FileUtil(File parent, String child) throws NullPointerException {
          super(parent, child);
       public FileUtil(String pathname) throws NullPointerException {
          super(pathname);
       public FileUtil(String parent, String child) throws NullPointerException {
          super(parent, child);
       public FileUtil(URI uri) throws IllegalArgumentException, NullPointerException {
          super(uri);
       public void deleteTree() throws Exception {
          ArrayList contents = new ArrayList();
          listContents(contents);
          File f;
          for (int i = contents.size() - 1; i >= 0; i--) {
          f = new File( (String) contents.get(i));
          f.delete();
       private void listContents(ArrayList files) throws Exception {
          listContents(files, this);
       private void listContents(ArrayList files, File dir) throws Exception {
          System.out.println(dir.getAbsolutePath());
          File[] newFiles = dir.listFiles();
          File newFile;
          if (newFiles != null) {
          for (int i = 0; i < newFiles.length; i++) {
             newFile = new File(newFiles.getAbsolutePath());
         files.add(newFiles[i].getAbsolutePath());
         if (newFile.isDirectory()) {
         listContents(files, newFile);

  • TS1702 some how my phone deleted an app --- My Secret Folder from my iPhone  How do I restore it and its contents  Thanks

    soem how my iphone deleted an app.  can I retore it and its contents?  How?  thanks

    Redownload it from the app store.

  • Can I recover my junk folder and its contents after I inadvertently deleted the folder, and then empties my trash?

    I inadvertently deleted my entire junk folder which contained some valuable messages. I then right clicked and deleted my trash. Can this junk folder or its messages be recovered?

    If your mail server has a browser interface (webmail access such as mail.google.com), do the messages show up there? Otherwise, there is probably nothing left to do.

  • How to resize a document and its contents?

    I'm having some trouble resizing a single page, and a single part of that page, on my document.
    First the details: My page dimensions are 800 x 1200. On top of that black background, there's textured layer measuring 760 x 130 at the top (for website's name/logo/misson statement) and 760 x 990 below (for site's content and graphics). There are 20 px borders (between textured layer and background) at the top and sides, and 10 px border at the bottom. The 50 px gap between the top and main textured areas is for the navigation bar.
    Now the problem: I want to resize just one page to 800 x 1250 px. And to complicate things, I only want to grow the bottom part by those 50 px, so that that textured layer measures 760 x 1040  (I have to add something to that page's main content, so I don't want to affect the size of either navigation bar or site's name/logo).
    Adobe instructions (http://help.adobe.com/en_US/Fireworks/10.0_Using/WSAE41683F-ED20-4488-9389-79DC28BD7CE0.ht ml) haven't been much help. I go to Modify > Canvas > Image Size, change to 1250 pixels, click off "constrain proportions" and click on "resample image" and "current page only." When I do that, it does enlarge both the black background and the textured layer to the size I want. But it also:
    1. Changes the entire page -- that is, it grows the nav bar and logo areas as well as the main content section.
    and, strangely,
    2. The textured layer on my two dozen other pages grows, but not the black background. In other words, I change both the background and layer size on the page I want to modify, but I inadvertently grow only the textured layer (but not background) on all of my other pages. (So the texture on all of those other pages now spills off the black background.)
    So my question: How can I resize only the main content's background and textured layer on one page? Is it even possible?
    Many thanks to anyone who can help. And my apologies for the lengthy explanation.  But I'm new to webdesign and Adobe Fireworks, and I wanted to be as clear as possible about the problem.
    PS If it matters, I'm using Fireworks CS4

    Thank you, Pixlar. However, I couldn't adjust the rectangle as you suggested, as it was on my master page. That was the problem I was having: Both the canvas and the texture layer I put on it (ie, the rectangle) were on the master page. I wanted to change the dimensions of both canvas and rectangle on only one page. Following Jim's suggestion, I was able to change the canvas, but not the rectangle (at least,not without adjusting the master page, which would have affected the layout of twenty other pages).
    I finally decided to follow your other suggestion: Delete the old one and start over.
    Thank you again for your help. Nice having a forum like this to turn to.

  • Removed a share folder and its contents

    I inadvertantly removed a share folder how can I restore it and all the documents which I believe were not deleted and must still be on the drive

    If you deleted a share, the files are deleted as well.   Only way I know to recover them is to remove the drive from the case and use a Linux data recovery tool. 

  • How to Delete Current Version and Its History

    Hi Gurus.
    I need help on such a case;
    Let's assume that;
    I have enabled versioning on a folder.
    I have uploaded a document as the first version.
    Then I uploaded a new version of this document as second version.
    At this moment i noticed that "oopss i uploaded wrong document, so i need delete it!!!"
    There is the problem. I need to delete current version of the document and also from the versionin history so I can't duplicate the first version of the document as current, becuase it's an error by me.
    As final case I need to have;
    1st version as current version,
    There is no 2nd verison...
    If I upload a new version after a while, it will be the 2nd version of the document; not the 3rd one so there will be no loss at versioning number....
    How can I realize it by using standard properties of KM or by code or by using a custom property like "my version"??
    Thank you for ur responses....

    Hi,
    some tips about versioning in EP Java:
    if (res.isVersioned()) {
              // get versions...
              IVersionHistory versions = res.getVersionHistory();
              if (versions != null) {
                for (int i = 0, size = versions.size(); i < size; i++) {
    IResource ver = versions.get(i);
    // now try to delete the version - haven't tried yet...
    if(ver.isrevision)
      ver.delete();
    hope this helps a bit,
    Romano

  • If I delete a folder from my MacBook Air after backing my computer up with TimeMachine, will the folder and its contents stay on the external drive the next time I back up my computer?

    It's my understanding that TimeMachine intelligently backups computer system onto an external hard drive and keeps the backup up to date. Currently my MacBook Air is almost out of memory, so I was hoping to move all of my pictures and music to an external hard drive via TimeMachine and then delete the files from my laptop. As TimeMachine continues to backup my computer over the weeks and months after, will it see that the files are no longer on my computer and then delete them from my hard drive? I just don't want to lose the music and pictures I'm deleting in order to make more room.

    Time Machine won't delete them from the backup drive until it runs out of space, but other things can. Put them on a second external drive and set Time Machine to back it up as well.
    (110783)

  • How to restore an album and its content? (suddenly disappeared)

    I've just got my new macbook air and i imported a lot of photos to iPhoto
    and it took me so much time to arrange it by my order (different albums places times and faces).
    after a few days it suddenly won't open and it asks to choose an album or create one. i was trying to choose the old one but it won't open so i pressed "create new".
    I managed to restore my old photos but i am so mad! its not in the order and not in its places, its messy and doesnt arranged by how i did it before.
    no albums, no faces, NO EVENTS. Also every one of the photos is titled weirdly with numbers and letters which werent like this when i first imported them.
    in the begining i liked how it was but now i am so angry and absolutely not pleased with how it all works on iphoto. if i wont find a solution i would have to delete everything and start from zero.
    what can i do to restore my original album and all its events before it suddenly disappeared? if its even possible.
    thank you so much for help and sorry for my english.

    These are your options:
    1. Restore the iPhoto library from the most recent backup that predates the issue.
    2. Repair or rebuild the library.
    3. Scavenge the library with a third-party application called "iPhoto Library Manager," which you can find in a web search. From the application's menu bar (not the iPhoto menu bar), select
    Library ▹ Rebuild
    Books, calendars, and slideshows won't be preserved.

  • How do I restore mail and its contents

    I installed 10.10.1 and now Mail won't load.   Two Preference errors. 
    1.  There was an error in internet Accounts preferences.
    2.  Could not load iCloud preferences pane.
    Also I'm getting notifications that my start-up disc is full.  I delete files from Finder but it doesn't seem to change anything.

    Redownload it from the app store.

  • Powershell script for deleting sitecollection and its content db

     want to know whether any powershell script is avlble for deleting the sitecollection and its content db at oneshot!
    i have created sitecollection specific content db and i wanna delete the same.

    Hi,
    Below link will help to delete site collection
    http://technet.microsoft.com/en-us/library/cc262392(v=office.15).aspx
    Thanks
    Somnath Matere

Maybe you are looking for

  • Windows 7 Home Share Not Working Unless Logged In to Computer

    So my old computer with Windows Home Server blew up last week.  I bought a new computer with Windows 7 running and have everything set up. Here's the rub...  I cannot access my itunes home share unless I am logged in or remotely logged int to the com

  • Can't get Jump Cut to see Beat Markers

    I've watched several tutorials. I've tried this in a new project and I can ge it to work. I just can't get it to work in my existing project. I've put the music in the background where it's behind the video clips. I go into Clip Trimmer or what ever

  • Help! Titles wildly distorted after font change!

    I generated titles in LiveType, imported to FCP sequence, ouput on DVD with DVDSP. The font I used was Geneva. Unfortunately, I left it at 100% white, which wasn't smart. Result was that they flickered slightly. So, I went back to LiveType and re-did

  • Intune does not update the "Updates were installed" line on WU local screen

    On the main splash screen of WU, the Updates were installed line only changes when WU is run locally.  Updates via Intune do not register on this line item.  Very confusing and if you visit this screen with a client present, they might think that the

  • External Storage (hdd) is not detected after loading Mac OS X v10.7 Lion

    Dear All Everything was o'k with 10.6, but in 10.7 - it does not react at all. It is Seagate 500Gb. After connecting leds lit, but nothing more happens. Thanks in advance for your kind advices.