2012-04-03 93 views
0

我需要使用此循环来创建具有不同输出的不同文本文件。现在,它创建3个文件看起来像这样:在循环中创建多个FileWriter对象

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

我的想法是通过命名对象Fw[it]创建多个FileWriter类的对象,这样,因为我需要会有许多ojects。不幸的是,在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(); 
} 

回答

1

是创建FileWriter [] writers = new FileWriter [count]并将每个写入器放在其自己的插槽中

+0

谢谢,但我仍然得到相同的问题,它创建3个文件,看起来像这样:texts1.txt =一些文本,texts2.txt = texts1.txt +一些文本和texts3.txt = texts2.txt +一些文本。但它应该是这样的:texts1.txt =一些文本,texts2.txt =一些文本,texts3.txt =一些文本 – John 2012-04-03 23:06:13

0

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