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 */
017 package org.apache.commons.vfs2.provider.ram;
018
019 import java.io.IOException;
020 import java.io.OutputStream;
021
022 import org.apache.commons.vfs2.FileSystemException;
023
024 /**
025 * OutputStream to a RamFile.
026 * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a>
027 */
028 public class RamFileOutputStream extends OutputStream
029 {
030
031 /**
032 * File.
033 */
034 protected RamFileObject file;
035
036 /**
037 * buffer.
038 */
039 protected byte[] buffer1 = new byte[1];
040
041 /** File is open or closed */
042 protected boolean closed = false;
043
044 private IOException exc;
045
046 /**
047 * @param file The base file.
048 */
049 public RamFileOutputStream(RamFileObject file)
050 {
051 super();
052 this.file = file;
053 }
054
055 /*
056 * (non-Javadoc)
057 *
058 * @see java.io.DataOutput#write(byte[], int, int)
059 */
060 @Override
061 public void write(byte[] b, int off, int len) throws IOException
062 {
063 int size = this.file.getData().size();
064 int newSize = this.file.getData().size() + len;
065 // Store the Exception in order to notify the client again on close()
066 try
067 {
068 this.file.resize(newSize);
069 }
070 catch (IOException e)
071 {
072 this.exc = e;
073 throw e;
074 }
075 System.arraycopy(b, off, this.file.getData().getBuffer(), size, len);
076 }
077
078 /*
079 * (non-Javadoc)
080 *
081 * @see java.io.DataOutput#write(int)
082 */
083 @Override
084 public void write(int b) throws IOException
085 {
086 buffer1[0] = (byte) b;
087 this.write(buffer1);
088 }
089
090 @Override
091 public void flush() throws IOException
092 {
093 }
094
095 @Override
096 public void close() throws IOException
097 {
098 if (closed)
099 {
100 return;
101 }
102 // Notify on close that there was an IOException while writing
103 if (exc != null)
104 {
105 throw exc;
106 }
107 try
108 {
109 this.closed = true;
110 // Close the
111 this.file.endOutput();
112 }
113 catch (Exception e)
114 {
115 throw new FileSystemException(e);
116 }
117 }
118
119 }