package lecture.fileio;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import jp.avaj.lib.debug.L;

/**
 * Stringに文字列を書出す Java
 *
 * FileWriter⇒BufferedWriter⇒PrintWriterでテキストファイルに文字列を書出すことができる
 *     http://blogs.yahoo.co.jp/artery2020/40608092.html
 *     TextFileWrite.java
 *
 * 下記に示すようにStringWriter⇒BufferedWriter⇒PrintWriterでStringに文字列を書出すことができる
 * またPipedWriter⇒BufferedWriter⇒PrintWriterでパイプに文字列を書出すことができる
 * このようにファイル、String、パイプに書き出す処理を共通化することがでる
 * PrintWriterを使う上位の処理は同じてある
 *
 */
class TextWriteToString {
  public static void main(String[] args) throws IOException {
    String[] lines = new String[] {
      "line-1",
      "line-2",
      "line-3",
      "line-4"
    };
    StringWriter sw = null;
    BufferedWriter bw = null;
    PrintWriter pw = null;
    try {
      sw = new StringWriter();
      bw = new BufferedWriter(sw);
      pw = new PrintWriter(bw);
      for (int i=0; i<lines.length; i++) {
        pw.println(lines[i]);
      }
      // bwのバッファに余裕があるうちはswに書き出されないので強制的に書き出す
      bw.flush();
      L.p(sw.toString());
    }
    finally {
      if (pw != null) {
        pw.close();
      }
      if (bw != null) {
        bw.close();
      }
      if (sw != null) {
        sw.close();
      }
    }
  }
}
//---------------------------------------------------
//・目次 - ファイル入出力
//  http://blogs.yahoo.co.jp/artery2020/40607767.html
//・目次 - Java入門
//  http://blogs.yahoo.co.jp/artery2020/39975776.html
//・目次 - ビジネスパーソンの常識と非常識
//  http://blogs.yahoo.co.jp/artery2020/39728331.html
//・目次 - 論理・発想・思考についての考察と鍛え方
//  http://blogs.yahoo.co.jp/artery2020/39657784.html
//・目次 - 単なる雑談
//  http://blogs.yahoo.co.jp/artery2020/40599964.html
//---------------------------------------------------