1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  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. package org.apache.commons.net.io;
  17. import java.io.FilterOutputStream;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.net.Socket;
  21. /***
  22. * This class wraps an output stream, storing a reference to its originating
  23. * socket. When the stream is closed, it will also close the socket
  24. * immediately afterward. This class is useful for situations where you
  25. * are dealing with a stream originating from a socket, but do not have
  26. * a reference to the socket, and want to make sure it closes when the
  27. * stream closes.
  28. * <p>
  29. * <p>
  30. * @author Daniel F. Savarese
  31. * @see SocketInputStream
  32. ***/
  33. public class SocketOutputStream extends FilterOutputStream
  34. {
  35. private Socket __socket;
  36. /***
  37. * Creates a SocketOutputStream instance wrapping an output stream and
  38. * storing a reference to a socket that should be closed on closing
  39. * the stream.
  40. * <p>
  41. * @param socket The socket to close on closing the stream.
  42. * @param stream The input stream to wrap.
  43. ***/
  44. public SocketOutputStream(Socket socket, OutputStream stream)
  45. {
  46. super(stream);
  47. __socket = socket;
  48. }
  49. /***
  50. * Writes a number of bytes from a byte array to the stream starting from
  51. * a given offset. This method bypasses the equivalent method in
  52. * FilterOutputStream because the FilterOutputStream implementation is
  53. * very inefficient.
  54. * <p>
  55. * @param buffer The byte array to write.
  56. * @param offset The offset into the array at which to start copying data.
  57. * @param length The number of bytes to write.
  58. * @exception IOException If an error occurs while writing to the underlying
  59. * stream.
  60. ***/
  61. public void write(byte buffer[], int offset, int length) throws IOException
  62. {
  63. out.write(buffer, offset, length);
  64. }
  65. /***
  66. * Closes the stream and immediately afterward closes the referenced
  67. * socket.
  68. * <p>
  69. * @exception IOException If there is an error in closing the stream
  70. * or socket.
  71. ***/
  72. public void close() throws IOException
  73. {
  74. super.close();
  75. __socket.close();
  76. }
  77. }