【问题标题】:Variable filename in JavaJava中的变量文件名
【发布时间】:2014-01-20 19:43:02
【问题描述】:

有什么方法可以在每次循环时更改文件名? 假设我有以下示例代码:

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

现在我想在每次循环再次开始时将 output.txt 的名称更改为 output++.txt。

我现在会收到:

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

【问题讨论】:

    标签: java loops filenames printwriter


    【解决方案1】:

    您可以使用for 循环:

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

    【讨论】:

    • i &lt; n &amp;&amp; someCondition 可能是 OP 想要的(除非 someCondition 已经是一个计数器)。
    • @assylias:我认为这是someCondition。不过你可能是对的。
    • 我只是想知道这部分代码:"output" + i + ".txt" ,不知道这么简单。该条件不相关,因此我将其命名为 somecondition 以简化它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多