Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a directory and sub directory structure with java?

Tags:

Hello there I want to create the directories and sub directories with the java. My directory structure is starts from the current application directory, Means in current projects directory which looks like following...

Images    |    |+ Background    |    |+ Foreground           |           |+Necklace           |+Earrings           |+Etc... 

I know how to create directory but I need to create sub directory I tried with following code what should be next steps ?

File file = new File("Images"); file.mkdir(); 
like image 540
Gopal00005 Avatar asked Aug 07 '14 05:08

Gopal00005


People also ask

How do you create a directory in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.

How do I create a directory and file in Java?

In Java, we can use the File object to create a new folder or directory. The File class of Java provide a way through which we can make or create a directory or folder. We use the mkdir() method of the File class to create a new folder.

How do you create a recursive directory in Java?

Create an object of the File class with md as a parameter. Check if the directory already exists using the exists() method and display the message. Else create the directory using the mkdir()method. Make the recursive call.


2 Answers

You can use File.mkdir() or File.mkdirs() to create a directory. Between the two, the latter method is more tolerant and will create all intermediate directories as needed. Also, since I see that you use "\\" in your question, I would suggest using File.separator for a portable path separator string.

like image 68
Michael Aaron Safyan Avatar answered Jan 02 '23 20:01

Michael Aaron Safyan


Starting from Java 7, you can use the java.nio.file.Files & java.nio.file.Paths classes.

Path path = Paths.get("C:\\Images\\Background\\..\\Foreground\\Necklace\\..\\Earrings\\..\\Etc");  try {     Files.createDirectories(path); } catch (IOException e) {     System.err.println("Cannot create directories - " + e); } 

This is a tricky solution (because I used only one path to go to the whole structure).

If you don't like tricky solutions, you can use 4 simple paths instead:

Path p1 = Paths.get("C:\\Images\\Background"); Path p2 = Paths.get("C:\\Images\\Foreground\\Necklace"); Path p3 = Paths.get("C:\\Images\\Foreground\\Earrings"); Path p4 = Paths.get("C:\\Images\\Foreground\\Etc"); 

and then call the createDirectories method for all of them:

Files.createDirectories(p1); Files.createDirectories(p2); Files.createDirectories(p3); Files.createDirectories(p4); 
like image 31
ROMANIA_engineer Avatar answered Jan 02 '23 18:01

ROMANIA_engineer