Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Delete a directory recursively

  1. #1
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Delete a directory recursively

    Hi there again. I'm not able to delete the directory, only passing the programm 3 times it do:

    how my method works:


    1st time: delete all files
    2nd time: delete all directories, but no the file that invoke the method
    3nd time: delete the first directory

    how my method should work:
    1st time : delete all files and directories and the file that invoke, recursively

    static void deleteAll(File path){
    		if(path.isDirectory()){
                            //Found this condition (at the web) to delete own file that invoke but doesn't work for me
    			if(path.list().length == 0){   //Recursion end rule
    				path.delete();
    				return;
    			}
    			File[] directorio = path.listFiles();
    			for(int i=0; i<directorio.length ;i++){
                                    //Recursion rule
    				deleteAll(directorio[i]);
     
    			}
    		}
                    //Recursion end rule
    		else if(path.isFile())
    			path.delete();
    	}

    Thank you in advance


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,362
    Thanks
    49
    Thanked 2,207 Times in 2,180 Posts

    Default Re: Delete a directory recursively

    Do you have a testing driver for the code? A class with a main() and a method to create a folder and some files to be deleted.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Delete a directory recursively

    Yes, i test all in C:\ and i got these results, i have a main method, but the method "deleteAll" should do all the work. I used debugger many times, and tried to change the condition to delete directory into the for... out... and can't understand why doesn't work

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,362
    Thanks
    49
    Thanked 2,207 Times in 2,180 Posts

    Default Re: Delete a directory recursively

    Can you post the code for testing? It Should include a class, main() and a method to create folders and files to be deleted.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Delete a directory recursively

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
     
    public class Ejercicio04 {
    	public static void main(String[] args) {
    		try{
    			BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
    			if(args.length != 1 && args.length != 2){
    				System.err.println("Uso 1: java Ejercicio04 <fichero>");
    				System.err.println("Uso 2: java Ejercicio04 -r <directorio>");
    				return;
    			}
    			//Si se pasó un argumento, debe ser un archivo
    			if(args.length == 1){
    				File archivo = new File(args[0]);
    				//Si es un archivo
    				if(archivo.isFile()){
    					System.out.println("¿Está seguro de que desea borrar el archivo?(\"si\" = confirmar)");
    					String opcion = lector.readLine();
    					if(opcion.toLowerCase().equals("si"))
    						if(archivo.delete())
    							System.out.println("El archivo \""+archivo+"\" ha sido borrado correctamente.");
    						else
    							System.err.println("No se pudo borrar el archivo. Posiblemente no tenga permisos en esa carpeta.");
    					else
    						System.out.println("Se ha replanteado NO borrar el archivo.\nArchivo NO borrado.");
    				}
    				//Si no existe se notifica
    				else if(!archivo.exists())
    					System.err.println("El archivo no existe.");
    				//Si no es un archivo
    				else
    					System.err.println("Uso: java Ejercicio04 <fichero>");
     
    			}
    			//Si se pasaron dos argumentos, el primero debe ser -r y el segundo el nombre del directorio
    			else if(args.length == 2){
    				//El archivo será la posición que ocupe args[1]
    				File directorio = new File(args[1]);
    				if(args[0].equals("-r") && directorio.isDirectory()){
    					System.out.println("¿Está seguro de que desea borrar el directorio, y todo su contenido?(\"si\" = confirmar)");
    					String opcion = lector.readLine();
    					if(opcion.equals("si")){
    						deleteAll(directorio);
    						System.out.println("El directorio \""+directorio+"\" y todo su contenido, ha sido borrado correctamente.");
    					}
    					else
    						System.out.println("Se ha replanteado NO borrar el directorio.\nDirectorio NO borrado.");
     
    				}
    				else
    					System.err.println("Uso: java Ejercicio04 -r <directorio>");
    			}
    		}catch(IOException e){
    			System.err.println("Error de lectura / escritura");
    		}catch(Exception e){
    			System.err.println("Error.");
    		}
    	}
    	static void deleteAll(File path){
    		if(path.isDirectory()){
                            //Found this condition (at the web) to delete own file that invoke but doesn't work for me
    			if(path.list().length == 0){   //Recursion end rule
    				path.delete();
    				return;
    			}
    			File[] directorio = path.listFiles();
    			for(int i=0; i<directorio.length ;i++){
                                    //Recursion rule
    				deleteAll(directorio[i]);
     
    			}
    		}
                    //Recursion end rule
    		else if(path.isFile())
    			path.delete();
    	}

    usages:
    - java Ejercicio04 <file>
    - java Ejercicio04 -r <directory>

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,362
    Thanks
    49
    Thanked 2,207 Times in 2,180 Posts

    Default Re: Delete a directory recursively

    Where is the deleteAll() method in the code for compiling and testing?
    Where does the posted code create the files and directories to test deleteAll() with?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Delete a directory recursively

    edited, with translated method "deleteAll".
    Programm should delete directories recursively or a single file... that you pass as parameters, like "rm <file>" or "rm -r <directory" in linux console.
    It doesn't create the files. Excuse me.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,362
    Thanks
    49
    Thanked 2,207 Times in 2,180 Posts

    Default Re: Delete a directory recursively

    It doesn't create the files. Excuse me.
    It needs to so it can be tested.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Delete a directory recursively

    Will consider for next time. thank you. It is too late, must go sleep, see you next day .

Similar Threads

  1. Having trouble figuring out how to recursively do this.
    By javapenguin in forum What's Wrong With My Code?
    Replies: 17
    Last Post: May 1st, 2012, 09:50 PM
  2. How to copy files from one directory to another directory
    By kewlkeny in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: January 25th, 2012, 06:36 AM
  3. printing array recursively
    By kyros in forum Algorithms & Recursion
    Replies: 2
    Last Post: November 19th, 2010, 12:04 AM
  4. Can I delete one of these two?
    By ice in forum Java IDEs
    Replies: 2
    Last Post: November 14th, 2010, 03:02 AM
  5. Problem in recursion for Solving Maze Recursively program
    By _Coder1985 in forum Algorithms & Recursion
    Replies: 1
    Last Post: April 29th, 2009, 04:37 AM