How to delete a folder with files using Java

后端 未结 28 3443
北荒
北荒 2020-11-28 05:36

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.m         


        
28条回答
  •  清酒与你
    2020-11-28 05:48

    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();
            }
        }
    

提交回复
热议问题