1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void mkSingleDir(String dirPath, String dirName){ File file = new File(dirPath+dirName); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } }else{ System.out.println("Directory exists: "+file); } } |
Method to create multiple Folders/ Directories simultaneously:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void mkMultipleDir(String dirPath){ // Eg.: "C:\\Directory2\\Sub2\\Sub-Sub2" File files = new File(dirPath); if (!files.exists()) { if (files.mkdirs()) { System.out.println("Multiple directories are created!"); } else { System.out.println("Failed to create multiple directories!"); } }else{ System.out.println("Directory exists: "+file); } } |
(We will code the dynamic part of the new Folder/ Directory name here)
1 2 3 4 5 6 7 | public static void main(String[] args) { mkSingleDir("C:/Users/jigyasa/Desktop/","sampleDir2"); mkMultipleDir("C:/Users/jigyasa/Desktop/sampleDir3/sampleSubDir03"); String file = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss'.xls'").format(new Date()); System.out.println(file); } |
So basically, these methods will check weather the directory exists and create it if it does not. If the directory exists then the user will be prompted a message that the directory already exists and the path of the directory.
No comments:
Post a Comment