Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2010 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 com.android.gallery3d.util;
     18 
     19 import com.android.gallery3d.common.Utils;
     20 
     21 import java.io.IOException;
     22 import java.io.InterruptedIOException;
     23 import java.io.OutputStream;
     24 
     25 public class InterruptableOutputStream extends OutputStream {
     26 
     27     private static final int MAX_WRITE_BYTES = 4096;
     28 
     29     private OutputStream mOutputStream;
     30     private volatile boolean mIsInterrupted = false;
     31 
     32     public InterruptableOutputStream(OutputStream outputStream) {
     33         mOutputStream = Utils.checkNotNull(outputStream);
     34     }
     35 
     36     @Override
     37     public void write(int oneByte) throws IOException {
     38         if (mIsInterrupted) throw new InterruptedIOException();
     39         mOutputStream.write(oneByte);
     40     }
     41 
     42     @Override
     43     public void write(byte[] buffer, int offset, int count) throws IOException {
     44         int end = offset + count;
     45         while (offset < end) {
     46             if (mIsInterrupted) throw new InterruptedIOException();
     47             int bytesCount = Math.min(MAX_WRITE_BYTES, end - offset);
     48             mOutputStream.write(buffer, offset, bytesCount);
     49             offset += bytesCount;
     50         }
     51     }
     52 
     53     @Override
     54     public void close() throws IOException {
     55         mOutputStream.close();
     56     }
     57 
     58     @Override
     59     public void flush() throws IOException {
     60         if (mIsInterrupted) throw new InterruptedIOException();
     61         mOutputStream.flush();
     62     }
     63 
     64     public void interrupt() {
     65         mIsInterrupted = true;
     66     }
     67 }
     68