Home | History | Annotate | Download | only in build
      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.IOException;
     20 import java.io.InputStream;
     21 import java.io.OutputStream;
     22 
     23 import javax.annotation.Nonnull;
     24 
     25 /**
     26  * Class that continuously read an {@link InputStream} and optionally could write the input in a
     27  * {@link OutputStream}.
     28  */
     29 public class BytesStreamSucker {
     30 
     31   private static final int BUFFER_SIZE = 4096;
     32 
     33   @Nonnull
     34   private final byte[] buffer = new byte[BUFFER_SIZE];
     35 
     36   @Nonnull
     37   private final InputStream is;
     38 
     39   @Nonnull
     40   private final OutputStream os;
     41 
     42   private final boolean toBeClose;
     43 
     44   public BytesStreamSucker(
     45       @Nonnull InputStream is, @Nonnull OutputStream os, boolean toBeClose) {
     46     this.is = is;
     47     this.os = os;
     48     this.toBeClose = toBeClose;
     49   }
     50 
     51   public BytesStreamSucker(@Nonnull InputStream is, @Nonnull OutputStream os) {
     52     this(is, os, false);
     53   }
     54 
     55   public void suck() throws IOException {
     56     try {
     57       int bytesRead;
     58       while ((bytesRead = is.read(buffer)) >= 0) {
     59         os.write(buffer, 0, bytesRead);
     60         os.flush();
     61       }
     62     } finally {
     63       if (toBeClose) {
     64         os.close();
     65       }
     66     }
     67   }
     68 }