Search code examples
javatext-filesfilewriterprintwriter

Create New Text Files with Different Names in Java


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!");

        }
}

Solution

  • 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){
       }