ThresholdingOutputStream.java
上传用户:u_thks
上传日期:2022-07-31
资源大小:1910k
文件大小:2k
源码类别:

WEB源码(ASP,PHP,...)

开发平台:

Java

  1. package com.gamvan.fileUpload;
  2. import java.io.IOException;
  3. import java.io.OutputStream;
  4. public abstract class ThresholdingOutputStream
  5.     extends OutputStream
  6. {
  7.     private int threshold;
  8.     private long written;
  9.     private boolean thresholdExceeded;
  10.     public ThresholdingOutputStream(int threshold)
  11.     {
  12.         this.threshold = threshold;
  13.     }
  14.     public void write(int b) throws IOException
  15.     {
  16.         checkThreshold(1);
  17.         getStream().write(b);
  18.         written++;
  19.     }
  20.     public void write(byte b[]) throws IOException
  21.     {
  22.         checkThreshold(b.length);
  23.         getStream().write(b);
  24.         written += b.length;
  25.     }
  26.     public void write(byte b[], int off, int len) throws IOException
  27.     {
  28.         checkThreshold(len);
  29.         getStream().write(b, off, len);
  30.         written += len;
  31.     }
  32.     public void flush() throws IOException
  33.     {
  34.         getStream().flush();
  35.     }
  36.     public void close() throws IOException
  37.     {
  38.         try
  39.         {
  40.             flush();
  41.         }
  42.         catch (IOException ignored)
  43.         {
  44.             // ignore
  45.         }
  46.         getStream().close();
  47.     }
  48.     public int getThreshold()
  49.     {
  50.         return threshold;
  51.     }
  52.     public long getByteCount()
  53.     {
  54.         return written;
  55.     }
  56.     public boolean isThresholdExceeded()
  57.     {
  58.         return (written > threshold);
  59.     }
  60.     protected void checkThreshold(int count) throws IOException
  61.     {
  62.         if (!thresholdExceeded && (written + count > threshold))
  63.         {
  64.             thresholdReached();
  65.             thresholdExceeded = true;
  66.         }
  67.     }
  68.     protected abstract OutputStream getStream() throws IOException;
  69.     protected abstract void thresholdReached() throws IOException;
  70. }