Creating Folder/Directory if Doesn't Exist using Java

In some cases we may like to save a file inside a folder, in this case the application may result an error if the Folder/Directory is not available in the application directory. To over come this we can better create a folder with the name as per our wish.
This simple code first checks if the Folder/Directory with the desired name exists or not. If there is no such Folder/Directory then the code will create one Folder/Directory with the name defined.
Creating Directory/Folder if Doesn't Exist using Java
view plaincopy to clipboardprint?
  1. File theDir = new File("New Folder");  // Defining Directory/Folder Name  
  2. try{   
  3.     if (!theDir.exists()){  // Checks that Directory/Folder Doesn't Exists!  
  4.      boolean result = theDir.mkdir();    
  5.      if(result){  
  6.      JOptionPane.showMessageDialog(null"New Folder created!");}  
  7.     }  
  8. }catch(Exception e){  
  9.     JOptionPane.showMessageDialog(null, e);  
  10. }  

No comments:

Post a Comment