Create New Text Files with Different Names in Java

10,076

Solution 1

Check for the file. If exists then increment the index

File file = new File("E:\\" + "Person1" + ".txt");
int increase=1;
while(file.exists()){
     increase++;
     file = new File("E:\\" + "Person" + increase+ ".txt");
} 
if(!file.exists()) {
   try {

    String content = textfile.toString();
    file.createNewFile();

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();

    System.out.println("Done");

}catch (IOException e){
   }

Solution 2

Upon creating a new file, you should check if the file with such fileNumber or index already exists. While a file with such index exists, the index should be incremented. Finally, you create a new file with an index that does not exist.

Say you created an abstract representation of a file and now want to rename it to the first available index. Let's assume other files are located at C:\tmp:

File newFile;

int index = 1;
String parent = "C:\\tmp"
String name = "Person";
while ((newFile = new File(parent, name + index)).exists()) {
    index++;
}

/* Here you have a newFile with name set to the first available index */

Or if you want to consider having an extension:

File newFile;

int index = 1;
String parent = "C:\\tmp"
String name = "Person";
String extension = ".txt";
while ((newFile = new File(parent, name + index + extension)).exists()) {
    index++;
}

/* Here you have a newFile with name set to the first available index and extension */

UPDATE: Using the Java 8 NIO API, I've created the following method to return a Path object for the first available path that does not yet exist on the file system:

/**
 * Returns the first available {@code Path} with a unique file name. The
 * first available path means that, if a file with the specified
 * <tt>path</tt> exists on disk, an index is appended to it. If a file with
 * that path still exists, index is incremented and so on, until a unique
 * path is generated. This path is then returned.
 * <p>
 * If a file with the specified <tt>path</tt> does not exist, this method
 * trivially returns <tt>path</tt>.
 * <p>
 * For an example, if the parent directory of the specified path already
 * contains <tt>file.txt</tt>, <tt>file-0.txt</tt> and <tt>file-1.txt</tt>,
 * and the file name of this path is <tt>file.txt</tt>, then a path with
 * file name <tt>file-2.txt</tt> is returned.
 * 
 * @param path path from which the first available is returned
 * @return a path with a unique file name
 */
public static Path firstAvailable(Path path) {
    if (!Files.exists(path))
        return path;

    int namingIndex = 0;
    String name = path.getFileName().toString();
    String extension = "";

    int dotIndex = name.lastIndexOf('.');
    if (dotIndex > 0) {
        extension = name.substring(dotIndex);
        name = name.substring(0, dotIndex);
    }
    name += "-";

    while (Files.exists(path)) {
        path = path.resolveSibling(name + namingIndex + extension);
        namingIndex++;
    }
    return path;
}
Share:
10,076
AnotherUser
Author by

AnotherUser

Updated on June 04, 2022

Comments

  • AnotherUser
    AnotherUser almost 2 years

    Every time the code is executed I want a new Text File to be created.

    The Text File should be called Person1.

    Next time code is executed the Text File should be called Person2.

    Then again the Text File should be called Person3. etc, etc....

    At the moment, I'm able to create a Text File named "Person1" but can't create another Text File named "Person2".

    private int fileNumber = 1;
    fileNumber = fileNumber++;
    
    public static void main(String[] args) {
            try {
                FileWriter fw = new FileWriter("Person" + fileNumber + ".txt");
                PrintWriter pw = new PrintWriter(fw);
    
                pw.println("Hello you created a text file");
    
                pw.close();
            }
            catch (IOException e)
            {
                System.out.println("Error!");
    
            }
    }