001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.hadoop.io;
019    
020    import java.io.DataOutput;
021    import java.io.IOException;
022    import java.io.OutputStream;
023    
024    import org.apache.hadoop.classification.InterfaceAudience;
025    import org.apache.hadoop.classification.InterfaceStability;
026    
027    /**
028     * OutputStream implementation that wraps a DataOutput.
029     */
030    @InterfaceAudience.Public
031    @InterfaceStability.Unstable
032    public class DataOutputOutputStream extends OutputStream {
033    
034      private final DataOutput out;
035    
036      /**
037       * Construct an OutputStream from the given DataOutput. If 'out'
038       * is already an OutputStream, simply returns it. Otherwise, wraps
039       * it in an OutputStream.
040       * @param out the DataOutput to wrap
041       * @return an OutputStream instance that outputs to 'out'
042       */
043      public static OutputStream constructOutputStream(DataOutput out) {
044        if (out instanceof OutputStream) {
045          return (OutputStream)out;
046        } else {
047          return new DataOutputOutputStream(out);
048        }
049      }
050      
051      private DataOutputOutputStream(DataOutput out) {
052        this.out = out;
053      }
054      
055      @Override
056      public void write(int b) throws IOException {
057        out.writeByte(b);
058      }
059    
060      @Override
061      public void write(byte[] b, int off, int len) throws IOException {
062        out.write(b, off, len);
063      }
064    
065      @Override
066      public void write(byte[] b) throws IOException {
067        out.write(b);
068      }
069      
070    
071    }