1. /*
  2. * Copyright 1999-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.launcher;
  17. import java.io.InputStream;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. /**
  21. * A class for connecting an OutputStream to an InputStream.
  22. *
  23. * @author Patrick Luby
  24. */
  25. public class StreamConnector extends Thread {
  26. //------------------------------------------------------------------ Fields
  27. /**
  28. * Input stream to read from.
  29. */
  30. private InputStream is = null;
  31. /**
  32. * Output stream to write to.
  33. */
  34. private OutputStream os = null;
  35. //------------------------------------------------------------ Constructors
  36. /**
  37. * Specify the streams that this object will connect in the {@link #run()}
  38. * method.
  39. *
  40. * @param is the InputStream to read from.
  41. * @param os the OutputStream to write to.
  42. */
  43. public StreamConnector(InputStream is, OutputStream os) {
  44. this.is = is;
  45. this.os = os;
  46. }
  47. //----------------------------------------------------------------- Methods
  48. /**
  49. * Connect the InputStream and OutputStream objects specified in the
  50. * {@link #StreamConnector(InputStream, OutputStream)} constructor.
  51. */
  52. public void run() {
  53. // If the InputStream is null, don't do anything
  54. if (is == null)
  55. return;
  56. // Connect the streams until the InputStream is unreadable
  57. try {
  58. int bytesRead = 0;
  59. byte[] buf = new byte[4096];
  60. while ((bytesRead = is.read(buf)) != -1) {
  61. if (os != null && bytesRead > 0) {
  62. os.write(buf, 0, bytesRead);
  63. os.flush();
  64. }
  65. yield();
  66. }
  67. } catch (IOException e) {}
  68. }
  69. }