0

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

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

我的想法是FileWriter通过命名对象来创建多个类对象,Fw[it]以便我需要尽可能多的对象。不幸的是,在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();
}
4

2 回答 2

1

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

于 2012-04-03T18:56:58.360 回答
0

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

于 2012-04-03T23:57:24.867 回答