Ven Nilson
Ven Nilson

Reputation: 1019

Java: Create Directory with Loop

I make a program that create a directory on desktop with the name of world but i need 10 more directories in this world directory with the name of world1,world2 etc with the help of loop i enter loop but it doesn't create directories inside world. Code:

    public class A {

    public static void main(String[] args) {    

     File file = new File("C:\\Users\\xds\\Desktop\\world");

     for(int i=1;i<=10;i++){

     file.mkdirs();

        }
        }
        }

Upvotes: 0

Views: 1250

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38561

Nowhere in your code have you specified the creation of the sub directories. Try something like:

public class CreateDirectoryExample
{
    public static void main(String[] args) {    
        File worldDirectory = new File("C:\\Users\\xds\\Desktop\\world");
        if (!worldDirectory.exists()) {
            if (worldDirectory.mkdir()) {
                System.out.println("World directory is created!");
            } else {
                System.out.println("Failed to create World directory!");
            }
        }

        for(int i=1;i<=10;i++){
            File subWorldDir = new File("C:\\Users\\xds\\Desktop\\world\\" +i);
            if (!subWorldDir.exists()) {
                subWorldDir.mkdir();
                System.out.println("Created Sub World directory!");
            } else { 
                System.out.println("Failed to create Sub World directory!");
            }
        }

    }
}

Upvotes: 3

Abhi
Abhi

Reputation: 6588

Make a slight modification in the name by appending the i, this will create all directories.

public static void main(String[] args) {

        File file = null;

        for (int i = 1; i <= 10; i++) {
            file = new File("C:\\Users\\uszanr8\\Desktop\\world" + i);
            file.mkdirs();

        }
    }

Upvotes: 1

Related Questions