1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package util.build;
18 
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.io.PrintStream;
24 
25 import javax.annotation.Nonnull;
26 
27 /**
28  * Class that continuously read an {@link InputStream} and optionally could print the input in a
29  * {@link PrintStream}.
30  */
31 public class CharactersStreamSucker {
32 
33   @Nonnull
34   private final BufferedReader ir;
35 
36   @Nonnull
37   private final PrintStream os;
38 
39   private final boolean toBeClose;
40 
CharactersStreamSucker( @onnull InputStream is, @Nonnull PrintStream os, boolean toBeClose)41   public CharactersStreamSucker(
42       @Nonnull InputStream is, @Nonnull PrintStream os, boolean toBeClose) {
43     this.ir = new BufferedReader(new InputStreamReader(is));
44     this.os = os;
45     this.toBeClose = toBeClose;
46   }
47 
CharactersStreamSucker(@onnull InputStream is, @Nonnull PrintStream os)48   public CharactersStreamSucker(@Nonnull InputStream is, @Nonnull PrintStream os) {
49     this(is, os, false);
50   }
51 
suck()52   public void suck() throws IOException {
53     String line;
54 
55     try {
56       while ((line = ir.readLine()) != null) {
57         os.println(line);
58       }
59     } finally {
60       if (toBeClose) {
61         os.close();
62       }
63     }
64   }
65 }