Java/File Input Output/Writer

Материал из Java эксперт
Перейти к: навигация, поиск

A writer for char strings

   <source lang="java">

/* 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.
*/

/**

* A writer for char strings.
* 
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.9.0
*/

public class CharArrayWriter {

 protected char[] buffer;
 protected int count;
 public CharArrayWriter(char[] buffer) {
   this.buffer = buffer;
 }
 public void write(int c) {
   if (count == buffer.length) {
     ensureSize(count + 1);
   }
   buffer[count++] = (char) c;
 }
 void ensureSize(int size) {
   if (size <= buffer.length) {
     return;
   }
   int newSize = buffer.length;
   while (newSize < size) {
     newSize *= 2;
   }
   char[] newBuffer = new char[newSize];
   System.arraycopy(buffer, 0, newBuffer, 0, count);
   buffer = newBuffer;
 }
 public void write(String str, int off, int len) {
   ensureSize(count + len);
   str.getChars(off, off + len, buffer, count);
   count += len;
 }
 public void reset() {
   count = 0;
 }
 public void reset(char[] buffer) {
   count = 0;
   this.buffer = buffer;
 }
 public char[] toCharArray() {
   char[] newBuffer = new char[count];
   System.arraycopy(buffer, 0, newBuffer, 0, count);
   return (char[]) newBuffer;
 }
 public int size() {
   return count;
 }
 /**
  * Converts input data to a string.
  * 
  * @return the string.
  */
 public String toString() {
   return new String(buffer, 0, count);
 }

}

 </source>
   
  
 
  



Null Writer

   <source lang="java">
    

/*

 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 /dev/null).
*
* @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 {
   }

}



 </source>
   
  
 
  



Provides Closable semantics ordinarily missing in a java.io.CharArrayWriter

   <source lang="java">


/* 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.<p> * * Data is retrieved using toCharArray(), toCharArrayReader() * and toString(). <p> * * {@link #close() Closing} a ClosableCharArrayWriter prevents * further write operations, but all other operations will succeed until after * the first invocation of {@link #free() free()}.<p> * * Freeing a ClosableCharArrayWriter closes the writer and * releases its internal buffer, preventing successful invocation of all * operations, with the exception of size()<tt>, <tt>close(), * isClosed(), free() and isFreed(). <p> * * 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 Writer.close() 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. <p> * * 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 * size, in characters. * * @param size the initial size. * @exception IllegalArgumentException if size 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 IOException 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 <p>. * * @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 IOException 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. <p> * * The operation occurs as if by calling * str.getChars(off, off + len, buf, count). <p> * * @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 IOException 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. <p> * * @throws java.io.IOException if an I/O error occurs. * In particular, an IOException 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. <p> * * The operation occurs as if by calling out.write(buf, 0, count). * * @param out the writer to which to write the data. * @throws java.io.IOException if an I/O error occurs. * In particular, an IOException 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 IOException may be thrown * if this writer has been {@link #free() freed}. */ public synchronized int capacity() throws IOException { checkFreed(); return buf.length; } /** * Resets the count 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 IOException 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. <p> * * 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 IOException 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 count 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. <p> * * @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. <p> * * 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 IOException 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. <p> * * Other operations may continue to succeed until after the first invocation * of {@link #free() free()}. <p> * * @throws java.io.IOException if an I/O error occurs (default: never) */ public synchronized void close() throws IOException { closed = true; } /** * @return true if this writer is closed, else false */ public synchronized boolean isClosed() { return closed; } /** * Closes this object and releases the underlying buffer for * garbage collection. <p> * * @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 true if this writer is freed; else false. */ 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 original with the given * newLength. <p> * * @param original the object to copy * @param newLength the length of the copy * @return copy of original with the given newLength */ 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; } } </source>

Reads characters available from the Reader and returns these characters as a String object.

   <source lang="java">

/*

* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/

import java.io.CharArrayWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class Main {

 /**
  * Fully reads the characters available from the supplied Reader
  * and returns these characters as a String object.
  *
  * @param reader The Reader to read the characters from.
  * @return A String existing of the characters that were read.
  * @throws IOException If I/O error occurred.
  */
 public static final String readFully(Reader reader)
   throws IOException
 {
   CharArrayWriter out = new CharArrayWriter(4096);
   transfer(reader, out);
   out.close();
   return out.toString();
 }
 /**
  * Transfers all characters that can be read from in to
  * out.
  *
  * @param in The Reader to read characters from.
  * @param out The Writer to write characters to.
  * @return The total number of characters transfered.
  */
 public static final long transfer(Reader in, Writer out)
   throws IOException
 {
   long totalChars = 0;
   int charsInBuf = 0;
   char[] buf = new char[4096];
   while ((charsInBuf = in.read(buf)) != -1) {
     out.write(buf, 0, charsInBuf);
     totalChars += charsInBuf;
   }
   return totalChars;
 }

}

 </source>
   
  
 
  



String Buffer Writer

   <source lang="java">
   

// // $Id: StringBufferWriter.java,v 1.4 2004/05/09 20:33:04 gregwilkins Exp $ // Copyright 2001-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed 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;

/* ------------------------------------------------------------ */ /** A Writer to a StringBuffer.

*
* @version $Id: StringBufferWriter.java,v 1.4 2004/05/09 20:33:04 gregwilkins Exp $
* @author Greg Wilkins (gregw)
*/

public class StringBufferWriter extends Writer {

   /* ------------------------------------------------------------ */
   private StringBuffer _buffer;
   /* ------------------------------------------------------------ */
   /** Constructor. 
    */
   public StringBufferWriter()
   {
       _buffer=new StringBuffer();
   }
   
   /* ------------------------------------------------------------ */
   /** Constructor. 
    * @param buffer 
    */
   public StringBufferWriter(StringBuffer buffer)
   {
       _buffer=buffer;
   }
   /* ------------------------------------------------------------ */
   public void setStringBuffer(StringBuffer buffer)
   {
       _buffer=buffer;
   }
   
   /* ------------------------------------------------------------ */
   public StringBuffer getStringBuffer()
   {
       return _buffer;
   }
   
   /* ------------------------------------------------------------ */
   public void write(char c)
       throws IOException
   {
       _buffer.append(c);
   }
   
   /* ------------------------------------------------------------ */
   public void write(char[] ca)
       throws IOException
   {
       _buffer.append(ca);
   }
   
   
   /* ------------------------------------------------------------ */
   public void write(char[] ca,int offset, int length)
       throws IOException
   {
       _buffer.append(ca,offset,length);
   }
   
   /* ------------------------------------------------------------ */
   public void write(String s)
       throws IOException
   {
       _buffer.append(s);
   }
   
   /* ------------------------------------------------------------ */
   public void write(String s,int offset, int length)
       throws IOException
   {
       for (int i=0;i<length;i++)
           _buffer.append(s.charAt(offset+i));
   }
   
   /* ------------------------------------------------------------ */
   public void flush()
   {}
   /* ------------------------------------------------------------ */
   public void reset()
   {
       _buffer.setLength(0);
   }
   /* ------------------------------------------------------------ */
   public void close()
   {}

}



 </source>
   
  
 
  



Writes all characters from a Reader to a file using the default character encoding.

   <source lang="java">

/*

* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/

import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class Main {

 /**
  * Writes all characters from a Reader to a file using the default
  * character encoding.
  *
  * @param reader The Reader containing the data to write to the
  * file.
  * @param file The file to write the data to.
  * @return The total number of characters written.
  * @throws IOException If an I/O error occured while trying to write the
  * data to the file.
  * @see java.io.FileWriter
  */
 public static final long writeToFile(Reader reader, File file)
   throws IOException
 {
   FileWriter writer = new FileWriter(file);
   try {
     return transfer(reader, writer);
   }
   finally {
     writer.close();
   }
 }
 /**
  * Transfers all characters that can be read from in to
  * out.
  *
  * @param in The Reader to read characters from.
  * @param out The Writer to write characters to.
  * @return The total number of characters transfered.
  */
 public static final long transfer(Reader in, Writer out)
   throws IOException
 {
   long totalChars = 0;
   int charsInBuf = 0;
   char[] buf = new char[4096];
   while ((charsInBuf = in.read(buf)) != -1) {
     out.write(buf, 0, charsInBuf);
     totalChars += charsInBuf;
   }
   return totalChars;
 }

}

 </source>
   
  
 
  



Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when finished.

   <source lang="java">

/*

* 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.InputStream; import java.io.OutputStream; import java.io.Reader; 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 input 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( Reader input,
                           Writer writer ) throws IOException {
     boolean error = false;
     try {
         if (input != null) {
             char[] buffer = new char[1024];
             try {
                 int numRead = 0;
                 while ((numRead = input.read(buffer)) > -1) {
                     writer.write(buffer, 0, numRead);
                 }
             } finally {
                 input.close();
             }
         }
     } 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;
             }
         }
     }
 }

}

 </source>