1 18 package org.apache.tools.ant.util; 19 20 import java.io.File ; 21 import java.io.FileOutputStream ; 22 import java.io.IOException ; 23 import java.io.OutputStream ; 24 25 32 public class LazyFileOutputStream extends OutputStream { 33 34 private FileOutputStream fos; 35 private File file; 36 private boolean append; 37 private boolean alwaysCreate; 38 private boolean opened = false; 39 private boolean closed = false; 40 41 46 public LazyFileOutputStream(String name) { 47 this(name, false); 48 } 49 50 57 public LazyFileOutputStream(String name, boolean append) { 58 this(new File (name), append); 59 } 60 61 66 public LazyFileOutputStream(File f) { 67 this(f, false); 68 } 69 70 77 public LazyFileOutputStream(File file, boolean append) { 78 this(file, append, false); 79 } 80 81 89 public LazyFileOutputStream(File file, boolean append, 90 boolean alwaysCreate) { 91 this.file = file; 92 this.append = append; 93 this.alwaysCreate = alwaysCreate; 94 } 95 96 102 public void open() throws IOException { 103 ensureOpened(); 104 } 105 106 110 public synchronized void close() throws IOException { 111 if (alwaysCreate && !closed) { 112 ensureOpened(); 113 } 114 if (opened) { 115 fos.close(); 116 } 117 closed = true; 118 } 119 120 125 public void write(byte[] b) throws IOException { 126 write(b, 0, b.length); 127 } 128 129 136 public synchronized void write(byte[] b, int offset, int len) 137 throws IOException { 138 ensureOpened(); 139 fos.write(b, offset, len); 140 } 141 142 147 public synchronized void write(int b) throws IOException { 148 ensureOpened(); 149 fos.write(b); 150 } 151 152 private synchronized void ensureOpened() throws IOException { 153 if (closed) { 154 throw new IOException (file + " has already been closed."); 155 } 156 157 if (!opened) { 158 fos = new FileOutputStream (file.getAbsolutePath(), append); 159 opened = true; 160 } 161 } 162 } 163 | Popular Tags |