001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.vfs2.provider.ram; 018 019import java.io.IOException; 020import java.io.OutputStream; 021 022/** 023 * OutputStream to a RamFile. 024 */ 025public class RamFileOutputStream extends OutputStream { 026 027 /** 028 * File. 029 */ 030 protected RamFileObject file; 031 032 /** 033 * buffer. 034 */ 035 protected byte[] buffer1 = new byte[1]; 036 037 /** File is open or closed */ 038 protected boolean closed; 039 040 private IOException exception; 041 042 /** 043 * Constructs a new instance. 044 * 045 * @param file The base file. 046 */ 047 public RamFileOutputStream(final RamFileObject file) { 048 this.file = file; 049 } 050 051 @Override 052 public void close() throws IOException { 053 if (closed) { 054 return; 055 } 056 // Notify on close that there was an IOException while writing 057 if (exception != null) { 058 throw exception; 059 } 060 closed = true; 061 } 062 063 @Override 064 public void flush() throws IOException { 065 } 066 067 /* 068 * (non-Javadoc) 069 * 070 * @see java.io.DataOutput#write(byte[], int, int) 071 */ 072 @Override 073 public void write(final byte[] b, final int off, final int len) throws IOException { 074 final RamFileData data = file.getData(); 075 final int size = data.size(); 076 final int newSize = size + len; 077 // Store the Exception in order to notify the client again on close() 078 try { 079 file.resize(newSize); 080 } catch (final IOException e) { 081 exception = e; 082 throw e; 083 } 084 System.arraycopy(b, off, data.getContent(), size, len); 085 } 086 087 /* 088 * (non-Javadoc) 089 * 090 * @see java.io.DataOutput#write(int) 091 */ 092 @Override 093 public void write(final int b) throws IOException { 094 buffer1[0] = (byte) b; 095 this.write(buffer1); 096 } 097 098}