001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.io; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtIncompatible; 020import java.io.FilterOutputStream; 021import java.io.IOException; 022import java.io.OutputStream; 023 024/** 025 * An OutputStream that counts the number of bytes written. 026 * 027 * @author Chris Nokleberg 028 * @since 1.0 029 */ 030@GwtIncompatible 031public final class CountingOutputStream extends FilterOutputStream { 032 033 private long count; 034 035 /** 036 * Wraps another output stream, counting the number of bytes written. 037 * 038 * @param out the output stream to be wrapped 039 */ 040 public CountingOutputStream(OutputStream out) { 041 super(checkNotNull(out)); 042 } 043 044 /** Returns the number of bytes written. */ 045 public long getCount() { 046 return count; 047 } 048 049 @Override 050 public void write(byte[] b, int off, int len) throws IOException { 051 out.write(b, off, len); 052 count += len; 053 } 054 055 @Override 056 public void write(int b) throws IOException { 057 out.write(b); 058 count++; 059 } 060 061 // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior: 062 // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream. 063 // It should flush itself if necessary. 064 @Override 065 public void close() throws IOException { 066 out.close(); 067 } 068}