Jannic Beck
Jannic Beck

Reputation: 2425

Variable filename in Java

Is there any way you can change the name of a file each time doing a loop? Lets say I've got the following sample code:

while(somecondition) {    
    try (PrintWriter w = new PrintWriter("output.txt", "UTF-8");){
        w.println("Bye World");
    } 
}

Now i want to change the name of output.txt each time the loop starts again to output++.txt.

I would now receive:

output1.txt
output2.txt
output3.txt
outputn.txt

Upvotes: 0

Views: 2467

Answers (1)

Keppil
Keppil

Reputation: 46209

You can use a for loop:

for (int i = 1; i <= n && someCondition; i++) {    
    try (PrintWriter w = new PrintWriter("output" + i + ".txt", "UTF-8");){
        w.println("Bye World");
    } 
}

Upvotes: 3

Related Questions