/** * */ package uk.ac.vamsas.client.simpleclient; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.FileChannel; import org.apache.commons.logging.LogFactory; /** * @author Jim * */ public class LockedFileOutputStream extends FileOutputStream { private static org.apache.commons.logging.Log log = LogFactory.getLog(LockedFileOutputStream.class); //FileOutputStream ostream=null; boolean closed=true; private void init() { FileChannel ch = super.getChannel(); if (ch!=null) { try { closed = !ch.isOpen(); } catch (Exception e) { closed=true; log.debug("Invalid LockedOutputStream marked closed.",e); } } } /** * @param file * @throws FileNotFoundException */ public LockedFileOutputStream(File file) throws FileNotFoundException { super(file); // super(file); init(); } /** * @param file * @param append * @throws FileNotFoundException */ public LockedFileOutputStream(File file, boolean append) throws FileNotFoundException { super(file, append); init(); } /** * @param fdObj */ public LockedFileOutputStream(FileDescriptor fdObj) { super(fdObj); init(); if (fdObj.valid()) closed=false; } /** * @param name * @throws FileNotFoundException */ public LockedFileOutputStream(String name) throws FileNotFoundException { super(name); init(); } /** * @param name * @param append * @throws FileNotFoundException */ public LockedFileOutputStream(String name, boolean append) throws FileNotFoundException { super(name, append); init(); } /** * closes - actually just flushes the stream instead. */ public void close() throws IOException { if (!closed) { super.flush(); super.getChannel().force(true); log.debug("Marking Lockedoutputstream closed."); } else throw new IOException("Close on already closed FileOutputStream."); closed=true; } /** * @throws IOException * @see java.io.OutputStream#flush() */ public void flush() throws IOException { if (!closed) super.flush(); else throw new IOException("flush on closed FileOutputStream"); } /** * @return * @see java.io.FileOutputStream#getChannel() */ public FileChannel getChannel() { if (!closed) return super.getChannel(); else return null; } /** * @param b * @param off * @param len * @throws IOException * @see java.io.FileOutputStream#write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { if (!closed) super.write(b, off, len); else throw new IOException("write on Closed FileOutputStream"); } /** * @param b * @throws IOException * @see java.io.FileOutputStream#write(byte[]) */ public void write(byte[] b) throws IOException { if (!closed) super.write(b); else throw new IOException("write on Closed FileOutputStream"); } /** * @param b * @throws IOException * @see java.io.FileOutputStream#write(int) */ public void write(int b) throws IOException { if (!closed) super.write(b); else throw new IOException("write on Closed FileOutputStream"); } }