package org.terrier.indexing;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.Thread;

class StreamGobbler
extends Thread
{
  InputStream is;
  String file_path;
  boolean output_to_file;

  StreamGobbler(InputStream is)
  {
    this.is = is;
    this.output_to_file = false;
  }

  StreamGobbler(InputStream is, String file_path)
  {
    this.is = is;
    this.file_path = file_path;
    this.output_to_file = true;
  }

  public void run()
  {
    try
    {
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line = null;
      if (output_to_file)
      {
        PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file_path)));
        while ( (line = br.readLine()) != null)
        {
          pw.println(line);
        }
        pw.flush();
        pw.close();
      }
      else
      {
        while ( (line  = br.readLine()) != null)
        {
          // Do nothing - equivalent to > /dev/null
        }
      }
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
  }
}