Home | History | Annotate | Download | only in android_scripting
      1 /*
      2  * Copyright (C) 2016 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * 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, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License.
     15  */
     16 
     17 package com.googlecode.android_scripting;
     18 
     19 import java.io.BufferedInputStream;
     20 import java.io.BufferedOutputStream;
     21 import java.io.IOException;
     22 import java.io.InputStream;
     23 import java.io.OutputStream;
     24 
     25 public class IoUtils {
     26   private static final int BUFFER_SIZE = 1024 * 8;
     27 
     28   private IoUtils() {
     29     // Utility class.
     30   }
     31 
     32   public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
     33     byte[] buffer = new byte[BUFFER_SIZE];
     34 
     35     BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
     36     BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
     37     int count = 0, n = 0;
     38     try {
     39       while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
     40         out.write(buffer, 0, n);
     41         count += n;
     42       }
     43       out.flush();
     44     } finally {
     45       try {
     46         out.close();
     47       } catch (IOException e) {
     48         Log.e(e.getMessage(), e);
     49       }
     50       try {
     51         in.close();
     52       } catch (IOException e) {
     53         Log.e(e.getMessage(), e);
     54       }
     55     }
     56     return count;
     57   }
     58 
     59 }
     60