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
有帮助吗?

解决方案

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");
    } 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top