user8646082 user8646082 - 5 months ago 29
Java Question

Creating Directories and Sub directories and getting files inside sub directories

I am using this code to create directory and sub directories. I want my file Example.xml should come inside this subdirectory.
Instead of file I am getting folder of file name.


public class CreateDirectoryExample {

public static void main(String[] args) {

File file = new File("C:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");

File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2\\example.xml");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");



Please help

Answer Source

This thread contains answer to your question with multiple approaches. Create whole path automatically when writing to a new file. It will help to reduce your code significantly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download