001 /*--------------------------------------------------------------------------+ 002 $Id: StreamReaderThread.java 26283 2010-02-18 11:18:57Z juergens $ 003 | | 004 | Copyright 2005-2010 Technische Universitaet Muenchen | 005 | | 006 | Licensed under the Apache License, Version 2.0 (the "License"); | 007 | you may not use this file except in compliance with the License. | 008 | You may obtain a copy of the License at | 009 | | 010 | http://www.apache.org/licenses/LICENSE-2.0 | 011 | | 012 | Unless required by applicable law or agreed to in writing, software | 013 | distributed under the License is distributed on an "AS IS" BASIS, | 014 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 015 | See the License for the specific language governing permissions and | 016 | limitations under the License. | 017 +--------------------------------------------------------------------------*/ 018 package edu.tum.cs.commons.io; 019 020 import java.io.BufferedReader; 021 import java.io.IOException; 022 import java.io.InputStream; 023 import java.io.InputStreamReader; 024 025 /** 026 * A thread to drain an input stream. 027 * 028 * @author Elmar Juergens 029 * @author Florian Deissenboeck 030 * @author $Author: juergens $ 031 * @version $Rev: 26283 $ 032 * @levd.rating GREEN Hash: 25DAC0F50BA3CBA7C86127762780A8C4 033 */ 034 public class StreamReaderThread extends Thread { 035 036 /** Stream the reader reads from. */ 037 private final InputStream input; 038 039 /** Content read from the stream.. */ 040 private StringBuilder content; 041 042 /** 043 * Create a new reader that reads the content of this stream in its own 044 * thread. => This call is non- blocking 045 * 046 * @param input 047 * Stream to read from. 048 * 049 */ 050 public StreamReaderThread(InputStream input) { 051 super(); 052 this.input = input; 053 start(); 054 } 055 056 /** 057 * Reads content from the stream as long as the stream is not empty. 058 */ 059 @Override 060 public synchronized void run() { 061 BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 062 063 char[] buffer = new char[1024]; 064 065 content = new StringBuilder(); 066 067 try { 068 int read = 0; 069 while ((read = reader.read(buffer)) != -1) { 070 content.append(buffer, 0, read); 071 } 072 } catch (IOException e) { 073 // in case of a problem append exception description to result. 074 content.append(e); 075 } 076 077 } 078 079 /** Returns the content read from the stream. */ 080 public synchronized String getContent() { 081 return content.toString(); 082 } 083 }