• Post Reply Bookmark Topic Watch Topic
  • New Topic

creation and deletion of files and folders.  RSS feed

 
Ranganath Junpal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to delete the files and folders recursively can any one help me out here.. i tried out but its not happening consistant.. please if any one can give code ofr creation of files and folders recursively and deleting the folders and files recursively please let me know.

Thank you
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a rough sketch for creating a set of folders ...

// The main routine says ...
call createPath "one/two/three/four"

// The createPath method does something like ...
separate "one" from "two/three/four"
create directory "one"
call createPath "two/three/four"

When createPath calls itself we get recursion. The second time it will separate "two" from "three/four", create two, call itself again with "three/four". I didn't show a test in createPath to say when there's nothing left on the end simply return without calling itself. You do need that!

Are you ok with breaking up the string "one/two/three/four" into "one" and "two/three/four"? Are you ok with creating one directory? Give it a shot, post some code, show us where you are stuck.
[ March 20, 2007: Message edited by: Stan James ]
 
sachin poddar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and here is the whole code....
/**
* Delete a file. If file is a directory, delete it and all sub-directories.
*
* @param file file or directory to delete, not null
* @throws NullPointerException if the directory is null
* @throws IOException in case deletion is unsuccessful *
*/
public static void forceDelete(File file) throws IOException {
if(file.isDirectory()) {
File files[] = file.listFiles();
if(files == null) {// null if security restricted
throw new IOException("Failed to list contents of " + file);
}
for (int i = 0; i < files.length; i++) {
File tempFile = files[i];
forceDelete(tempFile);
}
if(!file.delete()) {
String message = "Unable to delete directory " + file ;
throw new IOException(message);
}
} else {
if(!file.exists()) {
throw new FileNotFoundException("File does not exist: " + file);
}
if(!file.delete()) {
String message = "Unable to delete file: " + file;
throw new IOException(message);
}
}
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!