是否可以在Java中创建BufferedWriter数组?

时间:2011-12-20 19:57:29

标签: java arrays

我有一个String关键字数组,我将其传递给一个方法,在该方法中,我遍历数组并执行一些分析,然后将一些文本输出到文件中。我希望文件的名称与关键字的名称相匹配,但是如果我只是在每次移动到数组中的下一个元素时创建一个新的BufferedWriter,就像这样:

for(int i = 0; i < array.length; i++) {
    BufferedWriter writer = new BufferedWriter(new PrintWriter(array[i] + ".txt"));
    ...
}

然后我不能第二次遍历for循环并且仍然保留我在上一次迭代中写的内容(这是我想要做的事情),因为在现有文件中创建新编写器会删除现有内容。

任何方式我都可以创建一个BufferedWriter对象数组,然后通过索引来匹配我用于String数组的每个元素的writer?

3 个答案:

答案 0 :(得分:3)

[[从评论转到答案,因为这与OP想要的一样。]]

BufferedWriter[] writers = new BufferedWriter[num];

然后使用BufferedWriter个实例填充数组。

答案 1 :(得分:1)

您无需维护多个BufferedWriter引用的列表。

只需在需要时创建并关闭一个:

for(int i = 0; i < array.length; i++) {
    if(/*condition if need to create file and write */) {
         BufferedWriter writer = new BufferedWriter(new PrintWriter(array[i] + ".txt"));
         // do the writings here
         // and at last close it
    }
}

如果您想维护BufferedWriter引用列表,那么我认为最好使用MapHashMap<String, BufferedWriter>)和do map.put(keyword, writer)。< / p>

Map<String, BufferedWriter> writers = new HashMap<String, BufferedWriter>();
//then store the writers there

//in the second loop
//and you simply look it up using the keyword
//if the writer exists for current keyword use it
//otherwise create a new one
//I guess it would also be good to go through the map closing all the writers once done

答案 2 :(得分:1)

如果我理解正确,您可以使用HashMap或HashSet将您的作家映射到关键词。

String [] myStringArray = ....
HashMap<String, BufferedWriter> writerMap = new HashMap<String, BufferedWriter>();

for(int i = 0; i < myStringArray.length; i++) {
  String keyword = myStringArray[i];
  BufferedWriter writer = writerMap.get(keyword);
  if(writer == null) {
    writer = new BufferedWriter(new FileWriter(keyword + ".txt");
    writerMap.put(keyword, writer);
  }
  writer.write(...);
}

不要忘记添加一个可以通过并关闭所有作家的清理方法。

public void cleanUp() {
  Set<String> keySet = writerMap.keySet();
  for(String key : keySet) {
    BufferedWriter writer = writerMap.get(key);
    if(writer != null) {
      try {
        writer.close();
      }
      catch(Throwable t) {
        t.printStackTrace();
      }
      writer = null;
    }
  }
}