简体   繁体   中英

Deleting all files and folders in directory except hidden files using java

I need to delete all the files and folders in a directory but i need to .svn folder in this so that i can commit and delete the folder everytime. My below code worked but it retains .svn parent folder only but rest of its child .svn folders are deleted

my code:

      if (pFile.exists() ) {
        System.out.println(pFile.getName());
        if (pFile.isDirectory()) {
            if (pFile.list().length == 0) {
                 System.out.println("0>"+pFile.getName());
                pFile.delete();
            } else {
                System.out.println("1>"+pFile.getName());
                String[] strFiles = pFile.list();

                for (String strFilename : strFiles) {
                    File fileToDelete = new File(pFile, strFilename);
                    System.out.println("2>"+fileToDelete.getName());
                    if(fileToDelete.getName()==".svn")
                    {
                        // Do Nothing
                        break;
                    }
                    else
                    {
                    delete(fileToDelete);
                    }
                }
            }
        } else {
             System.out.println("3>"+pFile.getName());
           pFile.delete();
        }
    }

Need to modify condition as below. Here break will stop loop where as continue will skip only current deletion (ie, folder as .svn)

 if(fileToDelete.getName()!=null && fileToDelete.getName().equals(".svn")){
     // Do Nothing
     continue;
}

You can use pFile.isHidden() to check if it is a hidden file. In addition you can list all files in a folder with File.listFiles() instead of File.list() so you dont have to create a new File.

The other suggestions should solve your issue else you say, you need to delete all files and folders in a directory. So may be you are deleting all child folders that contain .svn in them and so you dont see them remain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM