001 /* 002 * Copyright 2001-2005 The Apache Software Foundation 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package org.apache.commons.net.io; 017 018 import java.io.FilterOutputStream; 019 import java.io.IOException; 020 import java.io.OutputStream; 021 import java.net.Socket; 022 023 /*** 024 * This class wraps an output stream, storing a reference to its originating 025 * socket. When the stream is closed, it will also close the socket 026 * immediately afterward. This class is useful for situations where you 027 * are dealing with a stream originating from a socket, but do not have 028 * a reference to the socket, and want to make sure it closes when the 029 * stream closes. 030 * <p> 031 * <p> 032 * @author Daniel F. Savarese 033 * @see SocketInputStream 034 ***/ 035 036 public class SocketOutputStream extends FilterOutputStream 037 { 038 private Socket __socket; 039 040 /*** 041 * Creates a SocketOutputStream instance wrapping an output stream and 042 * storing a reference to a socket that should be closed on closing 043 * the stream. 044 * <p> 045 * @param socket The socket to close on closing the stream. 046 * @param stream The input stream to wrap. 047 ***/ 048 public SocketOutputStream(Socket socket, OutputStream stream) 049 { 050 super(stream); 051 __socket = socket; 052 } 053 054 055 /*** 056 * Writes a number of bytes from a byte array to the stream starting from 057 * a given offset. This method bypasses the equivalent method in 058 * FilterOutputStream because the FilterOutputStream implementation is 059 * very inefficient. 060 * <p> 061 * @param buffer The byte array to write. 062 * @param offset The offset into the array at which to start copying data. 063 * @param length The number of bytes to write. 064 * @exception IOException If an error occurs while writing to the underlying 065 * stream. 066 ***/ 067 public void write(byte buffer[], int offset, int length) throws IOException 068 { 069 out.write(buffer, offset, length); 070 } 071 072 073 /*** 074 * Closes the stream and immediately afterward closes the referenced 075 * socket. 076 * <p> 077 * @exception IOException If there is an error in closing the stream 078 * or socket. 079 ***/ 080 public void close() throws IOException 081 { 082 super.close(); 083 __socket.close(); 084 } 085 }