com.day.io.BufferedRAFOutputStream Maven / Gradle / Ivy
/*
* $Id: BufferedRAFOutputStream.java 12345 2004-08-22 04:56:09Z fielding $
*
* Copyright 1997-2004 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Day.
*/
package com.day.io;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.IOException;
/**
* Implements a buffered output stream on a random access file
*
* @version $Revision: 1.2 $
* @author tripod
* @since echidna
*/
public class BufferedRAFOutputStream extends OutputStream {
/** the buffer */
private final byte[] buffer = new byte[8192];
/** the raf */
private RandomAccessFile raf;
/** the starting position of the buffer in the raf */
private long bufferStart;
/** the end of valid data in the buffer */
private int bufferEnd;
/** dummy buffer for {@link #write(int)} */
private byte[] one = new byte[1];
/**
* Contructs a new output stream
* @param raf
*/
public BufferedRAFOutputStream(RandomAccessFile raf) throws IOException {
this.raf = raf;
bufferStart = raf.getFilePointer();
}
/**
* @see java.io.OutputStream#write(int)
*/
public void write(int b) throws IOException {
one[0] = (byte) b;
write(one, 0, 1);
}
/**
* @see java.io.OutputStream#write(byte[])
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* @see java.io.OutputStream#write(byte[], int, int)
*/
public void write(byte b[], int off, int len) throws IOException {
if (len>buffer.length-bufferEnd) {
flush();
raf.write(b, off, len);
} else {
System.arraycopy(b, off, buffer, bufferEnd, len);
bufferEnd+=len;
}
}
/**
* @see java.io.OutputStream#flush()
*/
public void flush() throws IOException {
raf.write(buffer, 0, bufferEnd);
bufferEnd=0;
bufferStart=raf.getFilePointer();
}
/**
* @see java.io.OutputStream#close()
*/
public void close() throws IOException {
flush();
raf=null;
}
/**
* Returns the current filepointer
* @return the current filepointer
*/
public long getFilePointer() {
return bufferStart + bufferEnd;
}
}