Java Tutorial/File/Writer — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:20, 1 июня 2010
Содержание
- 1 A string writer that is able to write large amounts of data.
- 2 Implementation of a fast Writer.
- 3 Null Writer
- 4 Provides Closable semantics ordinarily missing in a {@link java.io.CharArrayWriter}.
- 5 Writer
- 6 Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when finished.
A string writer that is able to write large amounts of data.
/**
*
* JFreeReport : a free Java reporting library
*
*
* Project Info: http://reporting.pentaho.org/
*
* (C) Copyright 2001-2007, by Object Refinery Ltd, Pentaho Corporation and Contributors.
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------
* MemoryStringWriter.java
* ------------
* (C) Copyright 2001-2007, by Object Refinery Ltd, Pentaho Corporation and Contributors.
*/
import java.io.IOException;
import java.io.Writer;
/**
* A string writer that is able to write large amounts of data. The original
* StringWriter contained in Java doubles its buffersize everytime the buffer
* overflows. This is nice with small amounts of data, but awfull for huge
* buffers.
*
* @author Thomas Morgner
*/
public class MemoryStringWriter extends Writer {
private int bufferIncrement;
private int cursor;
private char[] buffer;
private int maximumBufferIncrement;
/**
* Create a new character-stream writer whose critical sections will
* synchronize on the writer itself.
*/
public MemoryStringWriter() {
this(4096);
}
/**
* Create a new character-stream writer whose critical sections will
* synchronize on the writer itself.
*/
public MemoryStringWriter(final int bufferSize) {
this(bufferSize, bufferSize * 4);
}
public MemoryStringWriter(final int bufferSize, final int maximumBufferIncrement) {
this.maximumBufferIncrement = maximumBufferIncrement;
this.bufferIncrement = bufferSize;
this.buffer = new char[bufferSize];
}
/**
* Write a portion of an array of characters.
*
* @param cbuf
* Array of characters
* @param off
* Offset from which to start writing characters
* @param len
* Number of characters to write
* @throws java.io.IOException
* If an I/O error occurs
*/
public synchronized void write(final char[] cbuf, final int off, final int len)
throws IOException {
if (len < 0) {
throw new IllegalArgumentException();
}
if (off < 0) {
throw new IndexOutOfBoundsException();
}
if (cbuf == null) {
throw new NullPointerException();
}
if ((len + off) > cbuf.length) {
throw new IndexOutOfBoundsException();
}
ensureSize(cursor + len);
System.arraycopy(cbuf, off, this.buffer, cursor, len);
cursor += len;
}
private void ensureSize(final int size) {
if (this.buffer.length >= size) {
return;
}
final int computedSize = (int) Math.min((this.buffer.length + 1) * 1.5, this.buffer.length
+ maximumBufferIncrement);
final int newSize = Math.max(size, computedSize);
final char[] newBuffer = new char[newSize];
System.arraycopy(this.buffer, 0, newBuffer, 0, cursor);
this.buffer = newBuffer;
}
/**
* Flush the stream. If the stream has saved any characters from the various
* write() methods in a buffer, write them immediately to their intended
* destination. Then, if that destination is another character or byte stream,
* flush it. Thus one flush() invocation will flush all the buffers in a chain
* of Writers and OutputStreams. <p/> If the intended destination of this
* stream is an abstraction provided by the underlying operating system, for
* example a file, then flushing the stream guarantees only that bytes
* previously written to the stream are passed to the operating system for
* writing; it does not guarantee that they are actually written to a physical
* device such as a disk drive.
*
* @throws java.io.IOException
* If an I/O error occurs
*/
public void flush() throws IOException {
}
/**
* Close the stream, flushing it first. Once a stream has been closed, further
* write() or flush() invocations will cause an IOException to be thrown.
* Closing a previously-closed stream, however, has no effect.
*
* @throws java.io.IOException
* If an I/O error occurs
*/
public void close() throws IOException {
}
public int getCursor() {
return cursor;
}
public String toString() {
return new String(buffer, 0, cursor);
}
}
Implementation of a fast Writer.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.io.Writer;
/**
* Implementation of a fast Writer. It was originally taken from JspWriter
* and modified to have less syncronization going on.
*
* @author
* @author Anil K. Vijendran
* @version $Id: VelocityWriter.java 463298 2006-10-12 16:10:32Z henning $
*/
public final class VelocityWriter extends Writer
{
/**
* constant indicating that the Writer is not buffering output
*/
public static final int NO_BUFFER = 0;
/**
* constant indicating that the Writer is buffered and is using the
* implementation default buffer size
*/
public static final int DEFAULT_BUFFER = -1;
/**
* constant indicating that the Writer is buffered and is unbounded;
* this is used in BodyContent
*/
public static final int UNBOUNDED_BUFFER = -2;
private int bufferSize;
private boolean autoFlush;
private Writer writer;
private char cb[];
private int nextChar;
private static int defaultCharBufferSize = 8 * 1024;
/**
* Create a buffered character-output stream that uses a default-sized
* output buffer.
*
* @param writer Writer to wrap around
*/
public VelocityWriter(Writer writer)
{
this(writer, defaultCharBufferSize, true);
}
/**
* private constructor.
*/
private VelocityWriter(int bufferSize, boolean autoFlush)
{
this.bufferSize = bufferSize;
this.autoFlush = autoFlush;
}
/**
* This method returns the size of the buffer used by the JspWriter.
*
* @return the size of the buffer in bytes, or 0 is unbuffered.
*/
public int getBufferSize() { return bufferSize; }
/**
* This method indicates whether the JspWriter is autoFlushing.
*
* @return if this JspWriter is auto flushing or throwing IOExceptions on
* buffer overflow conditions
*/
public boolean isAutoFlush() { return autoFlush; }
/**
* Create a new buffered character-output stream that uses an output
* buffer of the given size.
*
* @param writer Writer to wrap around
* @param sz Output-buffer size, a positive integer
* @param autoFlush
*
* @exception IllegalArgumentException If sz is <= 0
*/
public VelocityWriter(Writer writer, int sz, boolean autoFlush)
{
this(sz, autoFlush);
if (sz < 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.writer = writer;
cb = sz == 0 ? null : new char[sz];
nextChar = 0;
}
/**
* Flush the output buffer to the underlying character stream, without
* flushing the stream itself. This method is non-private only so that it
* may be invoked by PrintStream.
*/
private final void flushBuffer() throws IOException
{
if (bufferSize == 0)
return;
if (nextChar == 0)
return;
writer.write(cb, 0, nextChar);
nextChar = 0;
}
/**
* Discard the output buffer.
*/
public final void clear()
{
nextChar = 0;
}
private final void bufferOverflow() throws IOException
{
throw new IOException("overflow");
}
/**
* Flush the stream.
* @throws IOException
*
*/
public final void flush() throws IOException
{
flushBuffer();
if (writer != null)
{
writer.flush();
}
}
/**
* Close the stream.
* @throws IOException
*
*/
public final void close() throws IOException {
if (writer == null)
return;
flush();
}
/**
* @return the number of bytes unused in the buffer
*/
public final int getRemaining()
{
return bufferSize - nextChar;
}
/**
* Write a single character.
* @param c
* @throws IOException
*
*/
public final void write(int c) throws IOException
{
if (bufferSize == 0)
{
writer.write(c);
}
else
{
if (nextChar >= bufferSize)
if (autoFlush)
flushBuffer();
else
bufferOverflow();
cb[nextChar++] = (char) c;
}
}
/**
* Our own little min method, to avoid loading
* <code>java.lang.Math</code> if we"ve run out of file
* descriptors and we"re trying to print a stack trace.
*/
private final int min(int a, int b)
{
return (a < b ? a : b);
}
/**
* Write a portion of an array of characters.
*
* Ordinarily this method stores characters from the given array into
* this stream"s buffer, flushing the buffer to the underlying stream as
* needed. If the requested length is at least as large as the buffer,
* however, then this method will flush the buffer and write the characters
* directly to the underlying stream. Thus redundant
* <code>DiscardableBufferedWriter</code>s will not copy data unnecessarily.
*
* @param cbuf A character array
* @param off Offset from which to start reading characters
* @param len Number of characters to write
* @throws IOException
*
*/
public final void write(char cbuf[], int off, int len)
throws IOException
{
if (bufferSize == 0)
{
writer.write(cbuf, off, len);
return;
}
if (len == 0)
{
return;
}
if (len >= bufferSize)
{
/* If the request length exceeds the size of the output buffer,
flush the buffer and then write the data directly. In this
way buffered streams will cascade harmlessly. */
if (autoFlush)
flushBuffer();
else
bufferOverflow();
writer.write(cbuf, off, len);
return;
}
int b = off, t = off + len;
while (b < t)
{
int d = min(bufferSize - nextChar, t - b);
System.arraycopy(cbuf, b, cb, nextChar, d);
b += d;
nextChar += d;
if (nextChar >= bufferSize)
if (autoFlush)
flushBuffer();
else
bufferOverflow();
}
}
/**
* Write an array of characters. This method cannot be inherited from the
* Writer class because it must suppress I/O exceptions.
* @param buf
* @throws IOException
*/
public final void write(char buf[]) throws IOException
{
write(buf, 0, buf.length);
}
/**
* Write a portion of a String.
*
* @param s String to be written
* @param off Offset from which to start reading characters
* @param len Number of characters to be written
* @throws IOException
*
*/
public final void write(String s, int off, int len) throws IOException
{
if (bufferSize == 0)
{
writer.write(s, off, len);
return;
}
int b = off, t = off + len;
while (b < t)
{
int d = min(bufferSize - nextChar, t - b);
s.getChars(b, b + d, cb, nextChar);
b += d;
nextChar += d;
if (nextChar >= bufferSize)
if (autoFlush)
flushBuffer();
else
bufferOverflow();
}
}
/**
* Write a string. This method cannot be inherited from the Writer class
* because it must suppress I/O exceptions.
* @param s
* @throws IOException
*/
public final void write(String s) throws IOException
{
if (s != null)
{
write(s, 0, s.length());
}
}
/**
* resets this class so that it can be reused
* @param writer
*
*/
public final void recycle(Writer writer)
{
this.writer = writer;
clear();
}
}
Null Writer
/*
Milyn - Copyright (C) 2006
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details:
http://www.gnu.org/licenses/lgpl.txt
*/
import java.io.Writer;
import java.io.IOException;
/**
* Null writer implementation.
* <p/>
* Data writen to this writer is swallowed (ala piping output to <i>/dev/null</i>).
*
* @author
*/
public class NullWriter extends Writer {
private Writer parentWriter;
public NullWriter() {
super();
}
public NullWriter(Object lock) {
super(lock);
}
public NullWriter(Writer parentWriter) {
super();
this.parentWriter = parentWriter;
}
public Writer getParentWriter() {
return parentWriter;
}
public void write(int c) throws IOException {
}
public void write(char cbuf[]) throws IOException {
}
public void write(String str) throws IOException {
}
public void write(String str, int off, int len) throws IOException {
}
public Writer append(CharSequence csq) throws IOException {
return this;
}
public Writer append(CharSequence csq, int start, int end) throws IOException {
return this;
}
public Writer append(char c) throws IOException {
return this;
}
public void write(char cbuf[], int off, int len) throws IOException {
}
public void flush() throws IOException {
}
public void close() throws IOException {
}
}
Provides Closable semantics ordinarily missing in a {@link java.io.CharArrayWriter}.
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Writer;
/**
* @todo - finer-grained synchronization to reduce average
* potential monitor contention
*/
/**
* Provides Closable semantics ordinarily missing in a
* {@link java.io.CharArrayWriter}.
*
* Accumulates output in a character array that automatically grows as needed.
*
* Data is retrieved using <tt>toCharArray()</tt>, <tt>toCharArrayReader()</tt>
* and <tt>toString()</tt>.
*
* {@link #close() Closing} a <tt>ClosableCharArrayWriter</tt> prevents
* further write operations, but all other operations will succeed until after
* the first invocation of {@link #free() free()}.
*
* Freeing a <tt>ClosableCharArrayWriter</tt> closes the writer and
* releases its internal buffer, preventing successful invocation of all
* operations, with the exception of <tt>size()<tt>, <tt>close()</tt>,
* <tt>isClosed()</tt>, <tt>free()</tt> and <tt>isFreed()</tt>.
*
* This class is especially useful when an accumulating writer must be
* handed off to an extenal client under contract that the writer should
* exhibit true Closable behaviour, both in response to internally tracked
* events and to client invocation of the <tt>Writer.close()</tt> method.
*
* @author boucherb@users
* @version 1.8.x
* @since 1.8.x
*/
public class ClosableCharArrayWriter extends Writer {
/**
* Data buffer.
*/
protected char[] buf;
/**
* # of valid characters in buffer.
*/
protected int count;
/**
* Whether this writer is closed.
*/
protected boolean closed;
/**
* Whether this writer is freed.
*/
protected boolean freed;
/**
* Creates a new writer.
*
* The buffer capacity is initially 32 characters, although its size
* automatically increases when necessary.
*/
public ClosableCharArrayWriter() {
this(32);
}
/**
* Creates a new writer with a buffer capacity of the specified
* <tt>size</tt>, in characters.
*
* @param size the initial size.
* @exception IllegalArgumentException if <tt>size</tt> is negative.
*/
public ClosableCharArrayWriter(int size) throws IllegalArgumentException {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: "
+ size); // NOI18N
}
buf = new char[size];
}
/**
* Writes the specified single character.
*
* @param c the single character to be written.
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #close() closed}.
*/
public synchronized void write(int c) throws IOException {
checkClosed();
int newcount = count + 1;
if (newcount > buf.length) {
buf = copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = (char) c;
count = newcount;
}
/**
* Writes the designated portion of the designated character array .
*
* @param c the source character sequence.
* @param off the start offset in the source character sequence.
* @param len the number of characters to write.
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #close() closed}.
*/
public synchronized void write(char c[], int off,
int len) throws IOException {
checkClosed();
if ((off < 0) || (off > c.length) || (len < 0)
|| ((off + len) > c.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buf.length) {
buf = copyOf(buf, Math.max(buf.length << 1, newcount));
}
System.arraycopy(c, off, buf, count, len);
count = newcount;
}
/**
* Efficiently writes the designated portion of the designated string.
*
* The operation occurs as if by calling
* <tt>str.getChars(off, off + len, buf, count)</tt>.
*
* @param str the string from which to write
* @param off the start offset in the string.
* @param len the number of characters to write.
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #close() closed}.
*/
public synchronized void write(String str, int off,
int len) throws IOException {
checkClosed();
int strlen = str.length();
if ((off < 0) || (off > strlen) || (len < 0) || ((off + len) > strlen)
|| ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buf.length) {
buf = copyOf(buf, Math.max(buf.length << 1, newcount));
}
str.getChars(off, off + len, buf, count);
count = newcount;
}
/**
* By default, does nothing.
*
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #close() closed}.
*/
public void flush() throws IOException {
checkClosed();
}
/**
* Writes the complete contents of this writer"s buffered data to the
* specified writer.
*
* The operation occurs as if by calling <tt>out.write(buf, 0, count)</tt>.
*
* @param out the writer to which to write the data.
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #free() freed}.
*/
public synchronized void writeTo(Writer out) throws IOException {
checkFreed();
if (count > 0) {
out.write(buf, 0, count);
}
}
/**
* Returns the current capacity of this writer"s data buffer.
*
* @return the current capacity (the length of the internal
* data array)
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #free() freed}.
*/
public synchronized int capacity() throws IOException {
checkFreed();
return buf.length;
}
/**
* Resets the <tt>count</tt> field of this writer to zero, so that all
* currently accumulated output is effectively discarded. Further write
* operations will reuse the allocated buffer space.
*
* @see #count
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this output stream has been {@link #close() closed}.
*/
public synchronized void reset() throws IOException {
checkClosed();
count = 0;
}
/**
* Attempts to reduce this writer"s buffer capacity to its current size.
*
* If the buffer is larger than necessary to hold its current sequence of
* characters, then it may be resized to become more space efficient.
* Calling this method may, but is not required to, affect the value
* returned by a subsequent call to the {@link #capacity()} method.
*/
public synchronized void trimToSize() throws IOException {
checkFreed();
if (buf.length > count) {
buf = copyOf(buf, count);
}
}
/**
* Creates a newly allocated character array. Its size is the current
* size of this writer and the valid contents of the buffer
* have been copied into it.
*
* @return the current contents of this writer, as a character array.
* @see #size()
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #free() freed}.
*/
public synchronized char[] toCharArray() throws IOException {
checkFreed();
return copyOf(buf, count);
}
/**
* Returns the current size of this writer"s accumulated character data.
*
* @return the value of the <tt>count</tt> field, which is the number
* of valid characters accumulated in this writer.
* @see #count
* @throws java.io.IOException never
*/
public synchronized int size() throws IOException {
return count;
}
/**
* Sets the size of this writer"s accumulated character data.
*
* @param newSize the new size of this writer"s accumulated data
* @throws ArrayIndexOutOfBoundsException if new size is negative
*/
public synchronized void setSize(int newSize) {
if (newSize < 0) {
throw new ArrayIndexOutOfBoundsException(newSize);
} else if (newSize > buf.length) {
buf = copyOf(buf, Math.max(buf.length << 1, newSize));
}
count = newSize;
}
/**
* Performs an effecient (zero-copy) conversion of the character data
* accumulated in this writer to a reader.
*
* To ensure the integrity of the resulting reader, {@link #free()
* free} is invoked upon this writer as a side-effect.
*
* @return a reader representing this writer"s accumulated
* character data
* @throws java.io.IOException if an I/O error occurs.
* In particular, an <tt>IOException</tt> may be thrown
* if this writer has been {@link #free() freed}.
*/
public synchronized CharArrayReader toCharArrayReader()
throws IOException {
checkFreed();
CharArrayReader reader = new CharArrayReader(buf, 0, count);
//System.out.println("toCharArrayReader::buf.length: " + buf.length);
free();
return reader;
}
/**
* Converts this writer"s accumulated data into a string.
*
* @return String constructed from this writer"s accumulated data
* @throws RuntimeException may be thrown if this writer has been
* {@link #free() freed}.
*/
public synchronized String toString() {
try {
checkFreed();
} catch (IOException ex) {
throw new RuntimeException(ex.toString());
}
return new String(buf, 0, count);
}
/**
* Closes this object for further writing.
*
* Other operations may continue to succeed until after the first invocation
* of {@link #free() free()}.
*
* @throws java.io.IOException if an I/O error occurs (default: never)
*/
public synchronized void close() throws IOException {
closed = true;
}
/**
* @return <tt>true</tt> if this writer is closed, else <tt>false</tt>
*/
public synchronized boolean isClosed() {
return closed;
}
/**
* Closes this object and releases the underlying buffer for
* garbage collection.
*
* @throws java.io.IOException if an I/O error occurs while closing
* this writer (default: never).
*/
public synchronized void free() throws IOException {
closed = true;
freed = true;
buf = null;
count = 0;
}
/**
* @return <tt>true</tt> if this writer is freed; else <tt>false</tt>.
*/
public synchronized boolean isFreed() {
return freed;
}
/**
* @throws java.io.IOException if this writer is closed.
*/
protected synchronized void checkClosed() throws IOException {
if (closed) {
throw new IOException("writer is closed."); // NOI18N
}
}
/**
* @throws java.io.IOException if this writer is freed.
*/
protected synchronized void checkFreed() throws IOException {
if (freed) {
throw new IOException("write buffer is freed."); // NOI18N
}
}
/**
* Retrieves a copy of <tt>original</tt> with the given
* <tt>newLength</tt>.
*
* @param original the object to copy
* @param newLength the length of the copy
* @return copy of <tt>original</tt> with the given <tt>newLength</tt>
*/
protected char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
}
Writer
- The abstract class "Writer" defines a stream used for writing characters.
- OutputStreamWriter translates the characters into byte streams using a given character set.
- FileWriter is a child class of OutputStreamWriter that provides a convenient way to write characters to a file.
- When using FileWriter you are forced to output characters using the computer"s encoding.
- A better alternative to FileWriter is PrintWriter.
- Writer deals with characters instead of bytes.
- Writer class has three write method overloads:
public void write (int b)
public void write (char[] text)
public void write (char[] text, int offset, int length)
public void write (String text)
public void write (String text, int offset, int length)
Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when finished.
/*
* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
/**
* @author Randall Hauch
*/
public class Main {
/**
* Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when
* finished.
*
* @param content the content to write to the writer; may be null
* @param writer the writer to which the content is to be written
* @throws IOException
* @throws IllegalArgumentException if the writer is null
*/
public static void write( String content,
Writer writer ) throws IOException {
boolean error = false;
try {
if (content != null) {
writer.write(content);
}
} catch (IOException e) {
error = true; // this error should be thrown, even if there is an error flushing/closing writer
throw e;
} catch (RuntimeException e) {
error = true; // this error should be thrown, even if there is an error flushing/closing writer
throw e;
} finally {
try {
writer.flush();
} catch (IOException e) {
if (!error) throw e;
} finally {
try {
writer.close();
} catch (IOException e) {
if (!error) throw e;
}
}
}
}
}