Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, December 22, 2015

How to delete a folder with files using Java

How to delete a folder with files using Java


I want to create and delete a directory using Java, but it isn't working.

File index = new File("/home/Work/Indexer1");  if (!index.exists()) {      index.mkdir();  } else {      index.delete();      if (!index.exists()) {          index.mkdir();      }  }  

Answer by Aniket Thakur for How to delete a folder with files using Java


Remove it from else part

File index = new File("/home/Work/Indexer1");  if (!index.exists())  {       index.mkdir();       System.out.println("Dir Not present. Creating new one!");  }  index.delete();  System.out.println("File deleted successfully");  

Answer by SpringLearner for How to delete a folder with files using Java


In this

index.delete();                if (!index.exists())                 {                     index.mkdir();                 }  

you are calling

 if (!index.exists())                     {                         index.mkdir();                     }  

after

index.delete();  

This means that you are creating the file again after deleting File.delete() returns a boolean value.So if you want to check then do System.out.println(index.delete()); if you get true then this means that file is deleted

File index = new File("/home/Work/Indexer1");    if (!index.exists())     {        index.mkdir();     }    else{        System.out.println(index.delete());//If you get true then file is deleted                if (!index.exists())         {           index.mkdir();// here you are creating again after deleting the file         }              }  

from the comments given below,the updated answer is like this

File f=new File("full_path");//full path like c:/home/ri      if(f.exists())      {          f.delete();      }      else      {          try {              //f.createNewFile();//this will create a file              f.mkdir();//this create a folder          } catch (Exception e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }  

Answer by Ruchira Gayan Ranaweera for How to delete a folder with files using Java


you can try as follows

  File dir = new File("path");     if (dir.isDirectory())     {           dir.delete();     }  

If there are sub folders inside your folder you may need to recursively delete them.

Answer by Cemron for How to delete a folder with files using Java


Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.

Use something like:

String[]entries = index.list();  for(String s: entries){      File currentFile = new File(index.getPath(),s);      currentFile.delete();  }  

Then you should be able to delete the folder by using index.delete() Untested!

Answer by Andrey Chaschev for How to delete a folder with files using Java


In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.

In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.

Answer by Indranil.Bharambe for How to delete a folder with files using Java


directry cannot simply delete if it has the files so you may need to delete the files inside first and then directory

public class DeleteFileFolder {    public DeleteFileFolder(String path) {        File file = new File(path);      if(file.exists())      {          do{              delete(file);          }while(file.exists());      }else      {          System.out.println("File or Folder not found : "+path);      }    }  private void delete(File file)  {      if(file.isDirectory())      {          String fileList[] = file.list();          if(fileList.length == 0)          {              System.out.println("Deleting Directory : "+file.getPath());              file.delete();          }else          {              int size = fileList.length;              for(int i = 0 ; i < size ; i++)              {                  String fileName = fileList[i];                  System.out.println("File path : "+file.getPath()+" and name :"+fileName);                  String fullPath = file.getPath()+"/"+fileName;                  File fileOrFolder = new File(fullPath);                  System.out.println("Full Path :"+fileOrFolder.getPath());                  delete(fileOrFolder);              }          }      }else      {          System.out.println("Deleting file : "+file.getPath());          file.delete();      }  }  

Answer by Panthro for How to delete a folder with files using Java


If you have subfolders, you will find troubles with the Cemron answers. so you should create a method that works like this:

private void deleteTempFile(File tempFile) {          try          {              if(tempFile.isDirectory()){                 File[] entries = tempFile.listFiles();                 for(File currentFile: entries){                     deleteTempFile(currentFile);                 }                 tempFile.delete();              }else{                 tempFile.delete();              }          getLogger().info("DELETED Temporal File: " + tempFile.getPath());          }          catch(Throwable t)          {              getLogger().error("Could not DELETE file: " + tempFile.getPath(), t);          }      }  

Answer by user1082668 for How to delete a folder with files using Java


Just a one liner.

import org.apache.commons.io.FileUtils;    FileUtils.deleteDirectory(new File(destination));  

Documentation here

Answer by Marcelo Lopes for How to delete a folder with files using Java


private void deleteFileOrFolder(File file){      try {          for (File f : file.listFiles()) {              f.delete();              deleteFileOrFolder(f);          }      } catch (Exception e) {          e.printStackTrace(System.err);      }  }  

Answer by JRA_TLL for How to delete a folder with files using Java


Using Apache Commons-IO, it is following one-liner:

import org.apache.commons.io.FileUtils;    FileUtils.forceDelete(new File(destination));  

This may be (slightly) more performant than FileUtils.deleteDirectory.

Answer by Jeff Learman for How to delete a folder with files using Java


This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

void deleteDir(File file) {      File[] contents = file.listFiles();      if (contents != null) {          for (File f : contents) {              deleteDir(f);          }      }      file.delete();  }  

Answer by Pierre Leme for How to delete a folder with files using Java


My basic recursive version, working with older versions of JDK:

public static void deleteFile(File element) {      if (element.isDirectory()) {          for (File sub : element.listFiles()) {              deleteFile(sub);          }      }      element.delete();  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.