View Javadoc
1   /*
2    * Copyright (C) 2011, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util.io;
12  
13  import java.io.IOException;
14  import java.io.OutputStream;
15  
16  /**
17   * Counts the number of bytes written.
18   */
19  public class CountingOutputStream extends OutputStream {
20  	private final OutputStream out;
21  	private long cnt;
22  
23  	/**
24  	 * Initialize a new counting stream.
25  	 *
26  	 * @param out
27  	 *            stream to output all writes to.
28  	 */
29  	public CountingOutputStream(OutputStream out) {
30  		this.out = out;
31  	}
32  
33  	/**
34  	 * Get current number of bytes written.
35  	 *
36  	 * @return current number of bytes written.
37  	 */
38  	public long getCount() {
39  		return cnt;
40  	}
41  
42  	/** {@inheritDoc} */
43  	@Override
44  	public void write(int val) throws IOException {
45  		out.write(val);
46  		cnt++;
47  	}
48  
49  	/** {@inheritDoc} */
50  	@Override
51  	public void write(byte[] buf, int off, int len) throws IOException {
52  		out.write(buf, off, len);
53  		cnt += len;
54  	}
55  
56  	/** {@inheritDoc} */
57  	@Override
58  	public void flush() throws IOException {
59  		out.flush();
60  	}
61  
62  	/** {@inheritDoc} */
63  	@Override
64  	public void close() throws IOException {
65  		out.close();
66  	}
67  }