javafile-iofile

Check if a file exists, and if so create a new file with a higher number


I'm trying to output a set of points that my program creates, and I would like to be able to run it multiple times without having to manually move the files or rename them.
The files that I output would have a name like "cluster-1.txt" (could be changed if needed). So I need my program to find out if a cluster output file exists, find the file with the highest number and create a file with a higher number.

For example, if the program is running for the first time it would check, find no file and create "cluster-0.txt"; if the program is running for the second time, it would check and find "cluster-0.txt" and create "cluster-1.txt"; if the program is running for the nth time, it would check and find the file with the highest n value and the create a file called "cluster-n+1.txt".

If possible it should ignore any missing files in the middle. So, if I have cluster-0.txt, cluster-10.txt, and cluster-11.txt it should create cluster-12.txt. This is not essential, though.


Solution

    1. Read all files in directory. class File
    2. Parse name of files and retrieve number. class String
    3. Choose only the highest number. class Integer and class Math
    4. If highest number exist create file-[highest number + 1].txt else cluster-1.txt