【问题标题】:Creating multiple FileWriter objects in a loop在循环中创建多个 FileWriter 对象
【发布时间】:2012-04-03 18:52:09
【问题描述】:

我需要使用这个循环来创建具有不同输出的不同文本文件。现在它创建了 3 个如下所示的文件:

texts1.txt = some text
texts2.txt = texts1.txt + some text
texts3.txt = texts2.txt + some text

我的想法是通过将对象命名为 Fw[it] 来创建多个 FileWriter 类对象,这样就可以有尽可能多的对象。不幸的是,在java中我不能这样做。 有没有其他方法可以在循环中创建多个 FileWriter 对象?

int count = 3;
for (int it = 0; it < count; it++) {
String xxx = "texts" + it + ".txt";
FileWriter Fw = new FileWriter(xxx);
Collections.shuffle(list);
Fw.write(met.prnt(list,temp));
Fw.close();
}

好的,它可以编译并运行,但是它仍然有同样的问题:它创建了 3 个如下所示的文件:

texts1.txt = some text
texts2.txt = texts1.txt + some text
texts3.txt = texts2.txt + some text

但是,应该是这样的:

texts1.txt = some text
texts2.txt = some text
texts3.txt = some text

现在代码如下所示:

int count = 3;
for (int it = 0; it < count; it++) {
Collections.shuffle(list);
String xxx = "texts" + it + ".txt";
FileWriter hah[] = new FileWriter[count];
hah[it] = new FileWriter(xxx,false);
hah[it].write(met.prnt(list,temp));
hah[it].flush();
hah[it].close();
}

【问题讨论】:

    标签: java loops iteration filewriter


    【解决方案1】:

    是的,创建一个 FileWriter[] writers = new FileWriter[count] 并将每个 writer 放在自己的插槽中

    【讨论】:

    • 谢谢,但我仍然遇到同样的问题,它创建了 3 个文件,如下所示: texts1.txt = some text, texts2.txt = texts1.txt + some text and texts3.txt = texts2.txt + 一些文字。然而它应该是这样的: texts1.txt = some text , texts2.txt = some text , texts3.txt = some text
    【解决方案2】:

    您的代码与您描述的不一样。这甚至是不可能的。写入的行没有使用文件名变量xxx。我也不明白为什么您制作了创建 FileWriters 数组的第二个版本,因为您一次仍然只使用一个。特别是当您在循环内创建数组时。

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多