001/*
002 * Copyright 2011-2012 Stephen Connolly.
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
017package org.jszip.pseudo.io;
018
019import java.io.IOException;
020import java.io.OutputStream;
021import java.nio.ByteBuffer;
022
023public class PseudoFileOutputStream extends OutputStream {
024    private final OutputStream delegate;
025
026    public PseudoFileOutputStream(PseudoFile file) throws IOException {
027        this.delegate = file.$newOutputStream();
028    }
029
030    public PseudoFileOutputStream(String filename) throws IOException {
031        this.delegate = PseudoFileSystem.current().getPseudoFile(filename).$newOutputStream();
032    }
033
034    public PseudoFileOutputStream(PseudoFile file, boolean append) throws IOException {
035        this.delegate = file.$newOutputStream(append);
036    }
037
038    public PseudoFileOutputStream(String filename, boolean append) throws IOException {
039        this.delegate = PseudoFileSystem.current().getPseudoFile(filename).$newOutputStream(append);
040    }
041
042    @Override
043    public void close() throws IOException {
044        delegate.close();
045    }
046
047    @Override
048    public void flush() throws IOException {
049        delegate.flush();
050    }
051
052    @Override
053    public void write(byte[] b) throws IOException {
054        delegate.write(b);
055    }
056
057    @Override
058    public void write(byte[] b, int off, int len) throws IOException {
059        delegate.write(b, off, len);
060    }
061
062    @Override
063    public void write(int b) throws IOException {
064        delegate.write(b);
065    }
066
067    public PseudoFileOutputChannel getChannel() {
068        return new PseudoFileOutputChannel() {
069            @Override
070            public int write(ByteBuffer src) throws IOException {
071                final int remaining = src.remaining();
072                delegate.write(src.array(), src.arrayOffset(), remaining);
073                src.position(src.position() + remaining);
074                return remaining;
075            }
076
077            public void close() throws IOException {
078                PseudoFileOutputStream.this.close();
079            }
080        };
081    }
082}