title: Using BufferedWriter to write to a string
body: <p>I am trying to use a <code>BufferedWriter</code> to switch between writing to a <code>File</code> and writing to a <code>String</code>, but I have never used a <code>BufferedWriter</code> to write to anything but a file.</p>
  
  <p>Take this compilable code:</p>
  
  <pre><code>public static void main(String[] args) {
      try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(new File("file.txt")));
              StringWriter sw = new StringWriter();
              BufferedWriter stringWriter = new BufferedWriter(sw)) {
  
          LinkedList&lt;Record&gt; records = new LinkedList&lt;&gt;();
          records.add(new Record("name1", "text1", 20.4));
          records.add(new Record("name2", "text2", -78));
          records.add(new Record("name3", "text3", 11.56));
          records.add(new Record("name4", "text4", 56));
          records.add(new Record("name3", "text3", -44));
  
          for(Record record : records) {
              BufferedWriter writer;
              if(record.amount &lt; 0) {
                  writer = stringWriter; // write to string if amount is less than zero
              } else {
                  writer = fileWriter; // write to file if not
              }
  
              writer.append(record.name);
              writer.append(",");
              writer.append(record.text);
              writer.append(",");
              writer.append(String.valueOf(record.amount));
              writer.newLine();
  
          }
  
          String less_than_zero_amounts = sw.toString();
          System.out.println("Less than zero:" + less_than_zero_amounts);
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
  static class Record {
      String name;
      String text;
      double amount;
  
      public Record(String name, String text, double amount) {
          this.name = name;
          this.text = text;
          this.amount = amount;
      }
  
      public String getText() {
          return text;
      }
  
      public String getName() {
          return name;
      }
  
      public double getAmount() {
          return amount;
      }
  }
  </code></pre>
  
  <p>The output for the file is (correctly)</p>
  
  <pre><code>name1,text1,20.4
  name3,text3,11.56
  name4,text4,56.0
  </code></pre>
  
  <p>But the output for the program does not print the <code>StringWriter</code>.</p>
  
  <p>Admittedly, using a <code>StringWriter</code> and giving that to the <code>BufferedWriter</code> was a hunch. Any way I can switch a <code>BufferedWriter</code> to output to a <code>String</code> would solve the problem.</p>