user2666872
user2666872

Reputation: 33

Auto generate folder if the given one exists on a certain path

What i need to do is generate a folder with another name if the already given one exists on a certain path (for example if folder1 exists, it should create another one named folder2 and the second time you play the program folder3 etc etc).

The problem is i'm quite a rookie with java and i just know how to create the folder via mkdirs.

I've tried with "isDirectory()" but i must be missing the point.

Could you give me a BIG hand on this please?

Upvotes: 0

Views: 103

Answers (2)

Pradeep Simha
Pradeep Simha

Reputation: 18133

How about like this? File class has a exists() method which allows you to achieve what you are trying.

File folder= new File("C:\\YourExisitingFolder");

if(folder.exists()) {
   File folder2 = new File("C:\\YourNewFolder2");
   //Here you can create any pattern for creating new directory
   //For eg: appending numbers etc.
   folder2.mkdir() 
 }

Upvotes: 1

npinti
npinti

Reputation: 52195

To check if a file or folder exists, you can use the .exists() method exposed by the File Class.

public boolean exists()

Tests whether the file or directory denoted by this abstract pathname exists.

Returns: true if and only if the file or directory denoted by this abstract pathname exists; false otherwise

To check what number you need to use next, what comes to mind is that you can either:

  • Use some other file to store settings between applications. When the application resumes, you can load information from this file and keep on going. This usually helps if you need to keep track of things other than the file number.

  • You can have some smart logic which given a file name, it will see if it ends with a number and if it does, extract it, increment it and use it in the name of the next folder. This of course, assumes that the file name per se will not contain any numbers (other than the ones you add).

If I were to suggest, I'd go with the first option.

Upvotes: 0

Related Questions