Java/File Input Output/File Reader
Содержание
- 1 A StraightStreamReader is a bridge from byte streams to character streams
- 2 A word counting utility with FileReader.
- 3 Compare the contents of two Readers to determine if they are equal or not.
- 4 File Locking
- 5 Getting channels from streams
- 6 Indent - prepend leading spaces
- 7 Loading text from a file
- 8 Open File By Name
- 9 Read a file and print, using BufferedReader and System.out
- 10 Read a file containing an offset, and a String at that offset
- 11 Read and return the entire contents of the supplied Reader. This method always closes the reader when finished reading.
- 12 Reader for the ISO-8859-1 encoding.
- 13 Reader for UCS-2 and UCS-4 encodings. (i.e., encodings from ISO-10646-UCS-(2|4)).
- 14 Read file upside down
- 15 Read from Reader and write to Writer until there is no more input from reader.
- 16 Reading Numbers from a Text File
- 17 Reading Numbers from a Text File, Line by Line
- 18 Reads sequentially from multiple sources
- 19 Read the file one buffer at a time
- 20 Testing for end of file while reading a byte at a time
- 21 This class is an part implementation of DataInput. It wraps a Reader object.
- 22 Use a FileReader to display a text file.
A StraightStreamReader is a bridge from byte streams to character streams
<source lang="java">
/*
* An InputStreamReader that does no character encoding translations. * Copyright (C) 2001 Stephen Ostermiller * http://ostermiller.org/contact.pl?regarding=Java+Utilities * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * See COPYING.TXT for details. */
import java.io.*; /**
* A StraightStreamReader is a bridge from byte streams to character streams: It reads bytes * and translates them into characters without using a character encoding. The characters * that a StraightStreamReader returns may not be valid Unicode characters but they are * guaranteed to be in the 0x00 to 0xFF range. * More information about this class is available from .*
* Most of the time you want to do character encoding translation when translating bytes to
* characters. If you are planning on displaying the text, you should always do this and should
* use an InputStreamReader for the purpose. Sometimes it is useful to treat characters as bytes
* with some extra bits. In these cases you would want to use a StraightStreamReader.
* <P>
* For top efficiency, consider wrapping an StraightStreamReader within a BufferedReader. For example:
* BufferedReader in = new BufferedReader(new StraightStreamReader(System.in));
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StraightStreamReader extends Reader{
/**
* The input stream from which all methods in this class read.
*
* @since ostermillerutils 1.00.00
*/
private InputStream in;
/**
* A byte array to be used for calls to the InputStream. This
* is cached as a class variable to avoid object creation and
* deletion each time a read is called. This buffer may be
* null and may not be large enough. Make sure to check i
* before using it.
*
* @since ostermillerutils 1.00.00
*/
private byte[] buffer;
/**
* Create a StraightStreamReader from an InputStream
*
* @param in InputStream to wrap a Reader around.
*
* @since ostermillerutils 1.00.00
*/
public StraightStreamReader(InputStream in) {
this.in = in;
}
/**
* Close the stream.
*
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public void close() throws IOException {
in.close();
}
/**
* Mark the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point. Not all
* character-input streams support the mark() operation.
*
* @param readAheadLimit Limit on the number of characters that may be read
* while still preserving the mark. After reading this many characters,
* attempting to reset the stream may fail.
* @throws IOException If the stream does not support mark(), or if some other I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public void mark(int readAheadLimit) throws IOException {
in.mark(readAheadLimit);
}
/**
* Tell whether this stream supports the mark() operation.
*
* @return true if and only if this stream supports the mark operation.
*
* @since ostermillerutils 1.00.00
*/
@Override public boolean markSupported(){
return in.markSupported();
}
/**
* Read a single character. This method will block until a character is available, an
* I/O error occurs, or the end of the stream is reached.
*
* @return The character read, as an integer in the range 0 to 256 (0x00-0xff), or -1 if
* the end of the stream has been reached
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public int read() throws IOException {
return in.read();
}
/**
* Read characters into an array. This method will block until some input is available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param cbuf Destination buffer
* @return The number of bytes read, or -1 if the end of the stream has been reached
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public int read(char[] cbuf) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/**
* Read characters into an array. This method will block until some input is available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The number of bytes read, or -1 if the end of the stream has been reached
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public int read(char[] cbuf, int off, int len) throws IOException {
// ensure the capacity of the buffer that we will be using
// to read from the input stream
if (buffer == null || buffer.length < len){
buffer = new byte[len];
}
// read from the input stream and copy it to the character array
int length = in.read(buffer, 0, len);
for (int i=0; i<length; i++){
cbuf[off+i] = (char)(0xFF & buffer[i]);
}
return length;
}
/**
* Tell whether this stream is ready to be read.
*
* @return True if the next read() is guaranteed not to block for input, false otherwise.
* Note that returning false does not guarantee that the next read will block.
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public boolean ready() throws IOException {
return (in.available() > 0);
}
/**
* Reset the stream. If the stream has been marked, then attempt to reposition it at the mark.
* If the stream has not been marked, then attempt to reset it in some way appropriate to the
* particular stream, for example by repositioning it to its starting point. Not all
* character-input streams support the reset() operation, and some support reset()
* without supporting mark().
*
* @throws IOException If the stream has not been marked, or if the mark has been invalidated,
* or if the stream does not support reset(), or if some other I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public void reset() throws IOException {
in.reset();
}
/**
* Skip characters. This method will block until some characters are available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @throws IllegalArgumentException If n is negative
* @throws IOException If an I/O error occurs
*
* @since ostermillerutils 1.00.00
*/
@Override public long skip(long n) throws IOException {
return in.skip(n);
}
}
</source>
A word counting utility with FileReader.
<source lang="java">
import java.io.FileReader; class WordCount {
public static void main(String args[]) throws Exception { int words = 0; int lines = 0; int chars = 0; FileReader fr = new FileReader("yourFile.txt"); int c = 0; boolean lastWhite = true; String whiteSpace = " \t\n\r"; while ((c = fr.read()) != -1) { chars++; if (c == "\n") { lines++; } int index = whiteSpace.indexOf(c); if (index == -1) { if (lastWhite == true) { ++words; } lastWhite = false; } else { lastWhite = true; } } if (chars != 0) { ++lines; } }
}
</source>
Compare the contents of two Readers to determine if they are equal or not.
<source lang="java">
/*
* 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.BufferedReader; import java.io.IOException; import java.io.Reader; /** * Origin of code: Apache Avalon (Excalibur)
* * @author Peter Donald * @author Jeff Turner * @author Matthew Hawthorne * @author Stephen Colebourne * @author Gareth Davis * @version CVS $Revision$ $Date$*/
public class Main {
/**
* Compare the contents of two Readers to determine if they are equal or not.
* <p>
* This method buffers the input internally using BufferedReader
if they are not
* already buffered.
*
* @param input1
* the first reader
* @param input2
* the second reader
* @return true if the content of the readers are equal or they both don"t exist, false
* otherwise
* @throws NullPointerException
* if either input is null
* @throws IOException
* if an I/O error occurs
* @since 1.1
*/
public static boolean contentEquals(Reader input1, Reader input2) throws IOException
{
if (!(input1 instanceof BufferedReader))
{
input1 = new BufferedReader(input1);
}
if (!(input2 instanceof BufferedReader))
{
input2 = new BufferedReader(input2);
}
int ch = input1.read();
while (-1 != ch)
{
int ch2 = input2.read();
if (ch != ch2)
{
return false;
}
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
}
</source>
File Locking
<source lang="java">
// : c12:FileLocking.java // {Clean: file.txt} // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.io.FileOutputStream; import java.nio.channels.FileLock; public class FileLocking {
public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("file.txt"); FileLock fl = fos.getChannel().tryLock(); if (fl != null) { System.out.println("Locked File"); Thread.sleep(100); fl.release(); System.out.println("Released Lock"); } fos.close(); }
} ///:~
</source>
Getting channels from streams
<source lang="java">
// : c12:GetChannel.java // Getting channels from streams // {Clean: data.txt} // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class GetChannel {
private static final int BSIZE = 1024; public static void main(String[] args) throws Exception { // Write a file: FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); // Add to the end of the file: fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); // Move to the end fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); // Read the file: fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); }
} ///:~
</source>
Indent - prepend leading spaces
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 THE AUTHOR 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. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; /**
* Indent - prepend leading spaces * * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: Indent.java,v 1.3 2004/02/09 03:34:03 ian Exp $ */
public class Indent {
/** the default number of spaces. */ static int nSpaces = 10; public static void main(String[] av) { Indent c = new Indent(); switch (av.length) { case 0: c.process(new BufferedReader(new InputStreamReader(System.in))); break; default: for (int i = 0; i < av.length; i++) try { c.process(new BufferedReader(new FileReader(av[i]))); } catch (FileNotFoundException e) { System.err.println(e); } } } /** print one file, given an open BufferedReader */ public void process(BufferedReader is) { try { String inputLine; //+ while ((inputLine = is.readLine()) != null) { for (int i = 0; i < nSpaces; i++) System.out.print(" "); System.out.println(inputLine); } //- is.close(); } catch (IOException e) { System.out.println("IOException: " + e); } }
}
</source>
Loading text from a file
<source lang="java">
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Main {
public static void main(String[] argv) throws Exception { File f = new File("C:\\test.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); StringBuffer sb = new StringBuffer(); String eachLine = br.readLine(); while (eachLine != null) { sb.append(eachLine); sb.append("\n"); eachLine = br.readLine(); } System.out.println(sb.toString()); }
}
</source>
Open File By Name
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 THE AUTHOR 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. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.*; public class OpenFileByName {
public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new FileReader("myFile.txt")); BufferedOutputStream bytesOut = new BufferedOutputStream( new FileOutputStream("bytes.dat")); // Code here to read from is, write to bytesOut bytesOut.close(); }
}
</source>
Read a file and print, using BufferedReader and System.out
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 THE AUTHOR 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. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; /**
* Read a file and print, using BufferedReader and System.out */
public class CatFile {
public static void main(String[] av) { CatFile c = new CatFile(); if (av.length == 0) c.process(new BufferedReader(new InputStreamReader(System.in))); else for (int i = 0; i < av.length; i++) try { c.process(new BufferedReader(new FileReader(av[i]))); } catch (FileNotFoundException e) { System.err.println(e); } } /** print one file, given an open BufferedReader */ public void process(BufferedReader is) { try { String inputLine; while ((inputLine = is.readLine()) != null) { System.out.println(inputLine); } is.close(); } catch (IOException e) { System.out.println("IOException: " + e); } }
}
</source>
Read a file containing an offset, and a String at that offset
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 THE AUTHOR 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. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.IOException; import java.io.RandomAccessFile; /**
* Read a file containing an offset, and a String at that offset. * * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: ReadRandom.java,v 1.6 2004/03/07 17:30:35 ian Exp $ */
public class RandomRead {
final static String FILENAME = "random.dat"; protected String fileName; protected RandomAccessFile seeker; public static void main(String[] argv) throws IOException { RandomRead r = new RandomRead(FILENAME); System.out.println("Offset is " + r.readOffset()); System.out.println("Message is \"" + r.readMessage() + "\"."); } /** Constructor: save filename, construct RandomAccessFile */ public RandomRead(String fname) throws IOException { fileName = fname; seeker = new RandomAccessFile(fname, "r"); } /** Read the Offset field, defined to be at location 0 in the file. */ public int readOffset() throws IOException { seeker.seek(0); // move to very beginning return seeker.readInt(); // and read the offset } /** Read the message at the given offset */ public String readMessage() throws IOException { seeker.seek(readOffset()); // move to the offset return seeker.readLine(); // and read the String }
}
</source>
Read and return the entire contents of the supplied Reader. This method always closes the reader when finished reading.
<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.Reader; /**
* @author Randall Hauch */
public class Main {
/** * Read and return the entire contents of the supplied {@link Reader}. This method always closes the reader when finished * reading. * * @param reader the reader of the contents; may be null * @return the contents, or an empty string if the supplied reader is null * @throws IOException if there is an error reading the content */ public static String read( Reader reader ) throws IOException { if (reader == null) return ""; StringBuilder sb = new StringBuilder(); boolean error = false; try { int numRead = 0; char[] buffer = new char[1024]; while ((numRead = reader.read(buffer)) > -1) { sb.append(buffer, 0, numRead); } } catch (IOException e) { error = true; // this error should be thrown, even if there is an error closing reader throw e; } catch (RuntimeException e) { error = true; // this error should be thrown, even if there is an error closing reader throw e; } finally { try { reader.close(); } catch (IOException e) { if (!error) throw e; } } return sb.toString(); }
}
</source>
Reader for the ISO-8859-1 encoding.
<source lang="java">
/*
* 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.InputStream; import java.io.Reader; /**
* <p> * Reader for the ISO-8859-1 encoding.*
* * @xerces.internal * * @author Michael Glavassevich, IBM * * @version $Id: Latin1Reader.java 446716 2006-09-15 20:28:48Z mrglavas $ */
public class Latin1Reader extends Reader {
// // Constants // /** Default byte buffer size (2048). */ public static final int DEFAULT_BUFFER_SIZE = 2048; // // Data // /** Input stream. */ protected final InputStream fInputStream; /** Byte buffer. */ protected final byte[] fBuffer; // // Constructors // /** * Constructs an ISO-8859-1 reader from the specified input stream using the * default buffer size. * * @param inputStream * The input stream. */ public Latin1Reader(InputStream inputStream) { this(inputStream, DEFAULT_BUFFER_SIZE); } // <init>(InputStream) /** * Constructs an ISO-8859-1 reader from the specified input stream and buffer * size. * * @param inputStream * The input stream. * @param size * The initial buffer size. */ public Latin1Reader(InputStream inputStream, int size) { this(inputStream, new byte[size]); } // <init>(InputStream, int) /** * Constructs an ISO-8859-1 reader from the specified input stream and buffer. * * @param inputStream * The input stream. * @param buffer * The byte buffer. */ public Latin1Reader(InputStream inputStream, byte[] buffer) { fInputStream = inputStream; fBuffer = buffer; } // <init>(InputStream, byte[]) // // Reader methods // /** * Read a single character. This method will block until a character is * available, an I/O error occurs, or the end of the stream is reached. **
* Subclasses that intend to support efficient single-character input should * override this method. * * @return The character read, as an integer in the range 0 to 255 (0x00-0xff), * or -1 if the end of the stream has been reached * * @exception IOException * If an I/O error occurs */ public int read() throws IOException { return fInputStream.read(); } // read():int /** * Read characters into a portion of an array. This method will block until * some input is available, an I/O error occurs, or the end of the stream is * reached. * * @param ch * Destination buffer * @param offset * Offset at which to start storing characters * @param length * Maximum number of characters to read * * @return The number of characters read, or -1 if the end of the stream has * been reached * * @exception IOException * If an I/O error occurs */ public int read(char ch[], int offset, int length) throws IOException { if (length > fBuffer.length) { length = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, length); for (int i = 0; i < count; ++i) { ch[offset + i] = (char) (fBuffer[i] & 0xff); } return count; } // read(char[],int,int) /** * Skip characters. This method will block until some characters are * available, an I/O error occurs, or the end of the stream is reached. * * @param n * The number of characters to skip * * @return The number of characters actually skipped * * @exception IOException * If an I/O error occurs */ public long skip(long n) throws IOException { return fInputStream.skip(n); } // skip(long):long /** * Tell whether this stream is ready to be read. * * @return True if the next read() is guaranteed not to block for input, false * otherwise. Note that returning false does not guarantee that the * next read will block. * * @exception IOException * If an I/O error occurs */ public boolean ready() throws IOException { return false; } // ready() /** * Tell whether this stream supports the mark() operation. */ public boolean markSupported() { return fInputStream.markSupported(); } // markSupported() /** * Mark the present position in the stream. Subsequent calls to reset() will * attempt to reposition the stream to this point. Not all character-input * streams support the mark() operation. * * @param readAheadLimit * Limit on the number of characters that may be read while still * preserving the mark. After reading this many characters, * attempting to reset the stream may fail. * * @exception IOException * If the stream does not support mark(), or if some other I/O * error occurs */ public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); } // mark(int) /** * Reset the stream. If the stream has been marked, then attempt to reposition * it at the mark. If the stream has not been marked, then attempt to reset it * in some way appropriate to the particular stream, for example by * repositioning it to its starting point. Not all character-input streams * support the reset() operation, and some support reset() without supporting * mark(). * * @exception IOException * If the stream has not been marked, or if the mark has been * invalidated, or if the stream does not support reset(), or if * some other I/O error occurs */ public void reset() throws IOException { fInputStream.reset(); } // reset() /** * Close the stream. Once a stream has been closed, further read(), ready(), * mark(), or reset() invocations will throw an IOException. Closing a * previously-closed stream, however, has no effect. * * @exception IOException * If an I/O error occurs */ public void close() throws IOException { fInputStream.close(); } // close() } // class Latin1Reader </source>
Reader for UCS-2 and UCS-4 encodings. (i.e., encodings from ISO-10646-UCS-(2|4)).
<source lang="java">
/*
* 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.InputStream; import java.io.Reader; /**
* Reader for UCS-2 and UCS-4 encodings. (i.e., encodings from * ISO-10646-UCS-(2|4)). * * @xerces.internal * * @author Neil Graham, IBM * * @version $Id: UCSReader.java 449317 2006-09-23 22:12:30Z mrglavas $ */
public class UCSReader extends Reader {
// // Constants // /** * Default byte buffer size (8192, larger than that of ASCIIReader since it"s * reasonable to surmise that the average UCS-4-encoded file should be 4 times * as large as the average ASCII-encoded file). */ public static final int DEFAULT_BUFFER_SIZE = 8192; public static final short UCS2LE = 1; public static final short UCS2BE = 2; public static final short UCS4LE = 4; public static final short UCS4BE = 8; // // Data // /** Input stream. */ protected final InputStream fInputStream; /** Byte buffer. */ protected final byte[] fBuffer; // what kind of data we"re dealing with protected final short fEncoding; // // Constructors // /** * Constructs a UCS reader from the specified input stream using the default * buffer size. The Endian-ness and whether this is UCS-2 or UCS-4 needs also * to be known in advance. * * @param inputStream * The input stream. * @param encoding * One of UCS2LE, UCS2BE, UCS4LE or UCS4BE. */ public UCSReader(InputStream inputStream, short encoding) { this(inputStream, DEFAULT_BUFFER_SIZE, encoding); } // <init>(InputStream, short) /** * Constructs a UCS reader from the specified input stream and buffer size. * The Endian-ness and whether this is UCS-2 or UCS-4 needs also to be known * in advance. * * @param inputStream * The input stream. * @param size * The initial buffer size. * @param encoding * One of UCS2LE, UCS2BE, UCS4LE or UCS4BE. */ public UCSReader(InputStream inputStream, int size, short encoding) { this(inputStream, new byte[size], encoding); } // <init>(InputStream,int,short) /** * Constructs a UCS reader from the specified input stream and buffer. The * Endian-ness and whether this is UCS-2 or UCS-4 needs also to be known in * advance. * * @param inputStream * The input stream. * @param buffer * The byte buffer. * @param encoding * One of UCS2LE, UCS2BE, UCS4LE or UCS4BE. */ public UCSReader(InputStream inputStream, byte[] buffer, short encoding) { fInputStream = inputStream; fBuffer = buffer; fEncoding = encoding; } // <init>(InputStream,int,short) // // Reader methods // /** * Read a single character. This method will block until a character is * available, an I/O error occurs, or the end of the stream is reached. * * <p> * Subclasses that intend to support efficient single-character input should * override this method. * * @return The character read, as an integer in the range 0 to 127 (0x00-0x7f), * or -1 if the end of the stream has been reached * * @exception IOException * If an I/O error occurs */ public int read() throws IOException { int b0 = fInputStream.read() & 0xff; if (b0 == 0xff) { return -1; } int b1 = fInputStream.read() & 0xff; if (b1 == 0xff) { return -1; } // UCS-4 if (fEncoding >= 4) { int b2 = fInputStream.read() & 0xff; if (b2 == 0xff) { return -1; } int b3 = fInputStream.read() & 0xff; if (b3 == 0xff) { return -1; } if (fEncoding == UCS4BE) { return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; } return (b3 << 24) + (b2 << 16) + (b1 << 8) + b0; } // UCS-2 if (fEncoding == UCS2BE) { return (b0 << 8) + b1; } return (b1 << 8) + b0; } // read():int /** * Read characters into a portion of an array. This method will block until * some input is available, an I/O error occurs, or the end of the stream is * reached. * * @param ch * Destination buffer * @param offset * Offset at which to start storing characters * @param length * Maximum number of characters to read * * @return The number of characters read, or -1 if the end of the stream has * been reached * * @exception IOException * If an I/O error occurs */ public int read(char ch[], int offset, int length) throws IOException { int byteLength = length << ((fEncoding >= 4) ? 2 : 1); if (byteLength > fBuffer.length) { byteLength = fBuffer.length; } int count = fInputStream.read(fBuffer, 0, byteLength); if (count == -1) return -1; // try and make count be a multiple of the number of bytes we"re looking for if (fEncoding >= 4) { // BigEndian // this looks ugly, but it avoids an if at any rate... int numToRead = (4 - (count & 3) & 3); for (int i = 0; i < numToRead; i++) { int charRead = fInputStream.read(); if (charRead == -1) { // end of input; something likely went wrong!A Pad // buffer with nulls. for (int j = i; j < numToRead; j++) { fBuffer[count + j] = 0; } break; } fBuffer[count + i] = (byte) charRead; } count += numToRead; } else { int numToRead = count & 1; if (numToRead != 0) { count++; int charRead = fInputStream.read(); if (charRead == -1) { // end of input; something likely went wrong!A Pad // buffer with nulls. fBuffer[count] = 0; } else { fBuffer[count] = (byte) charRead; } } } // now count is a multiple of the right number of bytes int numChars = count >> ((fEncoding >= 4) ? 2 : 1); int curPos = 0; for (int i = 0; i < numChars; i++) { int b0 = fBuffer[curPos++] & 0xff; int b1 = fBuffer[curPos++] & 0xff; // UCS-4 if (fEncoding >= 4) { int b2 = fBuffer[curPos++] & 0xff; int b3 = fBuffer[curPos++] & 0xff; if (fEncoding == UCS4BE) { ch[offset + i] = (char) ((b0 << 24) + (b1 << 16) + (b2 << 8) + b3); } else { ch[offset + i] = (char) ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0); } } else { // UCS-2 if (fEncoding == UCS2BE) { ch[offset + i] = (char) ((b0 << 8) + b1); } else { ch[offset + i] = (char) ((b1 << 8) + b0); } } } return numChars; } // read(char[],int,int) /** * Skip characters. This method will block until some characters are * available, an I/O error occurs, or the end of the stream is reached. * * @param n * The number of characters to skip * * @return The number of characters actually skipped * * @exception IOException * If an I/O error occurs */ public long skip(long n) throws IOException { // charWidth will represent the number of bits to move // n leftward to get num of bytes to skip, and then move the result // rightward // to get num of chars effectively skipped. // The trick with &"ing, as with elsewhere in this dcode, is // intended to avoid an expensive use of / that might not be optimized // away. int charWidth = (fEncoding >= 4) ? 2 : 1; long bytesSkipped = fInputStream.skip(n << charWidth); if ((bytesSkipped & (charWidth | 1)) == 0) return bytesSkipped >> charWidth; return (bytesSkipped >> charWidth) + 1; } // skip(long):long /** * Tell whether this stream is ready to be read. * * @return True if the next read() is guaranteed not to block for input, false * otherwise. Note that returning false does not guarantee that the * next read will block. * * @exception IOException * If an I/O error occurs */ public boolean ready() throws IOException { return false; } // ready() /** * Tell whether this stream supports the mark() operation. */ public boolean markSupported() { return fInputStream.markSupported(); } // markSupported() /** * Mark the present position in the stream. Subsequent calls to reset() will * attempt to reposition the stream to this point. Not all character-input * streams support the mark() operation. * * @param readAheadLimit * Limit on the number of characters that may be read while still * preserving the mark. After reading this many characters, * attempting to reset the stream may fail. * * @exception IOException * If the stream does not support mark(), or if some other I/O * error occurs */ public void mark(int readAheadLimit) throws IOException { fInputStream.mark(readAheadLimit); } // mark(int) /** * Reset the stream. If the stream has been marked, then attempt to reposition * it at the mark. If the stream has not been marked, then attempt to reset it * in some way appropriate to the particular stream, for example by * repositioning it to its starting point. Not all character-input streams * support the reset() operation, and some support reset() without supporting * mark(). * * @exception IOException * If the stream has not been marked, or if the mark has been * invalidated, or if the stream does not support reset(), or if * some other I/O error occurs */ public void reset() throws IOException { fInputStream.reset(); } // reset() /** * Close the stream. Once a stream has been closed, further read(), ready(), * mark(), or reset() invocations will throw an IOException. Closing a * previously-closed stream, however, has no effect. * * @exception IOException * If an I/O error occurs */ public void close() throws IOException { fInputStream.close(); } // close()
} // class UCSReader
</source>
Read file upside down
<source lang="java">
import java.io.File; import java.io.FileReader; public class Main {
public static void main(String[] args) throws Exception { File f = new File("hello.txt"); FileReader fr = new FileReader(f); char[] c = new char[(int) f.length()]; char[] cnew = new char[(int) f.length()]; StringBuffer sbuf = new StringBuffer(); fr.read(c, 0, (int) f.length()); int len = (int) f.length(); for (int i = 0, j = len - 1; i < len; i++, j--) { cnew[i] = c[j]; sbuf.append(cnew[i]); } System.out.println(sbuf.toString()); fr.close(); }
}
</source>
Read from Reader and write to Writer until there is no more input from reader.
<source lang="java">
import java.io.IOException; import java.io.Reader; import java.io.Writer; public class Main {
/** * Read input from reader and write it to writer until there is no more * input from reader. * * @param reader the reader to read from. * @param writer the writer to write to. * @param buf the char array to use as a bufferx */ public static void flow( Reader reader, Writer writer, char[] buf ) throws IOException { int numRead; while ( (numRead = reader.read(buf) ) >= 0) { writer.write(buf, 0, numRead); } }
}
</source>
Reading Numbers from a Text File
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; // The buffering makes the program more than 20 times faster. public class SumFile {
public static void main(String[] a) throws IOException { sumfile("file.txt"); }
static void sumfile(String filename) throws IOException { Reader r = new BufferedReader(new FileReader(filename)); StreamTokenizer stok = new StreamTokenizer(r); stok.parseNumbers(); double sum = 0; stok.nextToken(); while (stok.ttype != StreamTokenizer.TT_EOF) { if (stok.ttype == StreamTokenizer.TT_NUMBER) sum += stok.nval; else System.out.println("Nonnumber: " + stok.sval); stok.nextToken(); } System.out.println("The file sum is " + sum); }
}
</source>
Reading Numbers from a Text File, Line by Line
<source lang="java">
import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.io.StreamTokenizer; public class SumLine {
public static void main(String[] a)throws IOException { sumLines("file.txt"); } static void sumLines(String filename) throws IOException { LineNumberReader lnr = new LineNumberReader(new FileReader(filename)); lnr.setLineNumber(1); StreamTokenizer stok = new StreamTokenizer(lnr); stok.parseNumbers(); stok.eolIsSignificant(true); stok.nextToken(); while (stok.ttype != StreamTokenizer.TT_EOF) { int lineno = lnr.getLineNumber(); double sum = 0; while (stok.ttype != StreamTokenizer.TT_EOL) { if (stok.ttype == StreamTokenizer.TT_NUMBER) sum += stok.nval; stok.nextToken(); } System.out.println("Sum of line " + lineno + " is " + sum); stok.nextToken(); } }
}
</source>
Reads sequentially from multiple sources
<source lang="java">
/*
* Copyright (C) 2004 Stephen Ostermiller * http://ostermiller.org/contact.pl?regarding=Java+Utilities * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * See COPYING.TXT for details. */
import java.io.*; import java.util.ArrayList; /**
* A reader which reads sequentially from multiple sources. * More information about this class is available from . * * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities * @since ostermillerutils 1.04.00 */
public class ConcatReader extends Reader {
/** * Current index to readerQueue * * @since ostermillerutils 1.04.01 */ private int readerQueueIndex = 0; /** * Queue of readers that have yet to be read from. * * @since ostermillerutils 1.04.01 */ private ArrayList<Reader> readerQueue = new ArrayList<Reader>(); /** * A cache of the current reader from the readerQueue * to avoid unneeded access to the queue which must * be synchronized. * * @since ostermillerutils 1.04.01 */ private Reader currentReader = null; /** * true iff the client may add more readers. * * @since ostermillerutils 1.04.01 */ private boolean doneAddingReaders = false; /** * Causes the addReader method to throw IllegalStateException * and read() methods to return -1 (end of stream) * when there is no more available data. * <p> * Calling this method when this class is no longer accepting * more readers has no effect. * * @since ostermillerutils 1.04.01 */ public void lastReaderAdded(){ doneAddingReaders = true; } /** * Add the given reader to the queue of readers from which to * concatenate data. * * @param in Reader to add to the concatenation. * @throws IllegalStateException if more readers can"t be added because lastReaderAdded() has been called, close() has been called, or a constructor with reader parameters was used. * * @since ostermillerutils 1.04.01 */ public void addReader(Reader in){ synchronized(readerQueue){ if (in == null) throw new NullPointerException(); if (closed) throw new IllegalStateException("ConcatReader has been closed"); if (doneAddingReaders) throw new IllegalStateException("Cannot add more readers - the last reader has already been added."); readerQueue.add(in); } } /** * Add the given reader to the queue of readers from which to * concatenate data. * * @param in Reader to add to the concatenation. * @throws IllegalStateException if more readers can"t be added because lastReaderAdded() has been called, close() has been called, or a constructor with reader parameters was used. * @throws NullPointerException the array of readers, or any of the contents is null. * * @since ostermillerutils 1.04.01 */ public void addReaders(Reader[] in){ for (Reader element: in) { addReader(element); } } /** * Gets the current reader, looking at the next * one in the list if the current one is null. * * @since ostermillerutils 1.04.01 */ private Reader getCurrentReader(){ if (currentReader == null && readerQueueIndex < readerQueue.size()){ synchronized(readerQueue){ // reader queue index is advanced only by the nextReader() // method. Don"t do it here. currentReader = readerQueue.get(readerQueueIndex); } } return currentReader; } /** * Indicate that we are done with the current reader and we should * advance to the next reader. * * @since ostermillerutils 1.04.01 */ private void advanceToNextReader(){ currentReader = null; readerQueueIndex++; } /** * True iff this the close() method has been called on this stream. * * @since ostermillerutils 1.04.00 */ private boolean closed = false; /** * Create a new reader that can dynamically accept new sources. * <p> * New sources should be added using the addReader() method. * When all sources have been added the lastReaderAdded() should * be called so that read methods can return -1 (end of stream). * <p> * Adding new sources may by interleaved with read calls. * * @since ostermillerutils 1.04.01 */ public ConcatReader(){ // Empty Constructor } /** * Create a new reader with one source. * <p> * When using this constructor, more readers cannot * be added later, and calling addReader() will * throw an illegal state Exception. * * @param in reader to use as a source. * * @throws NullPointerException if in is null * * @since ostermillerutils 1.04.00 */ public ConcatReader(Reader in){ addReader(in); lastReaderAdded(); } /** * Create a new reader with two sources. * <p> * When using this constructor, more readers cannot * be added later, and calling addReader() will * throw an illegal state Exception. * * @param in1 first reader to use as a source. * @param in2 second reader to use as a source. * * @throws NullPointerException if either source is null. * * @since ostermillerutils 1.04.00 */ public ConcatReader(Reader in1, Reader in2){ addReader(in1); addReader(in2); lastReaderAdded(); } /** * Create a new reader with an arbitrary number of sources. * <p> * When using this constructor, more readers cannot * be added later, and calling addReader() will * throw an illegal state Exception. * * @param in readers to use as a sources. * * @throws NullPointerException if the input array on any element is null. * * @since ostermillerutils 1.04.00 */ public ConcatReader(Reader[] in){ addReaders(in); lastReaderAdded(); } /** * Read a single character. This method will block until a * character is available, an I/O error occurs, or the end of all underlying * streams are reached. * <p> * If this class in not done accepting readers and the end of the last known * stream is reached, this method will block forever unless another thread * adds a reader or interrupts. * * @return The character read, as an integer in the range 0 to 65535 (0x00-0xffff), * or -1 if the end of the stream has been reached * * @throws IOException - If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public int read() throws IOException { if (closed) throw new IOException("Reader closed"); int r = -1; while (r == -1){ Reader in = getCurrentReader(); if (in == null){ if (doneAddingReaders) return -1; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { r = in.read(); if (r == -1) advanceToNextReader(); } } return r; } /** * Read characters into an array. This method will block until some input is available, an * I/O error occurs, or the end of all underlying * streams are reached. * <p> * If this class in not done accepting readers and the end of the last known * stream is reached, this method will block forever unless another thread * adds a reader or interrupts. * * @param cbuf - Destination buffer * @return The number of characters read, or -1 if the end of the stream has been reached * * @throws IOException - If an I/O error occurs * @throws NullPointerException - If the buffer is null. * * @since ostermillerutils 1.04.00 */ @Override public int read(char[] cbuf) throws IOException { return read(cbuf, 0, cbuf.length); } /** * Read characters into a portion of an array. This method will block until * some input is available, an I/O error occurs, or the end of all underlying * streams are reached. * <p> * If this class in not done accepting readers and the end of the last known * stream is reached, this method will block forever unless another thread * adds a reader or interrupts. * * @param cbuf Destination buffer * @param off Offset at which to start storing characters * @param len Maximum number of characters to read * @return The number of characters read, or -1 if the end of the stream has been reached * * @throws IOException - If an I/O error occurs * @throws NullPointerException - If the buffer is null. * @throws IndexOutOfBoundsException - if length or offset are not possible. * * @since ostermillerutils 1.04.00 */ @Override public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len > cbuf.length) throw new IndexOutOfBoundsException(); if (closed) throw new IOException("Reader closed"); int r = -1; while (r == -1){ Reader in = getCurrentReader(); if (in == null){ if (doneAddingReaders) return -1; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { r = in.read(cbuf, off, len); if (r == -1) advanceToNextReader(); } } return r; } /** * Skip characters. This method will block until some characters are * available, an I/O error occurs, or the end of the stream is reached. * <p> * If this class in not done accepting readers and the end of the last known * stream is reached, this method will block forever unless another thread * adds a reader or interrupts. * * @param n the number of characters to skip * @return The number of characters actually skipped * * @throws IllegalArgumentException If n is negative. * @throws IOException If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public long skip(long n) throws IOException { if (closed) throw new IOException("Reader closed"); if (n <= 0) return 0; long s = -1; while (s <= 0){ Reader in = getCurrentReader(); if (in == null){ if (doneAddingReaders) return 0; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { s = in.skip(n); // When nothing was skipped it is a bit of a puzzle. // The most common cause is that the end of the underlying // stream was reached. In which case calling skip on it // will always return zero. If somebody were calling skip // until it skipped everything they needed, there would // be an infinite loop if we were to return zero here. // If we get zero, let us try to read one character so // we can see if we are at the end of the stream. If so, // we will move to the next. if (s <= 0) { // read() will advance to the next stream for us, so don"t do it again s = ((read()==-1)?-1:1); } } } return s; } /** * Tell whether this stream is ready to be read. * * @return True if the next read() is guaranteed not to block for input, * false otherwise. Note that returning false does not guarantee that the next * read will block. * * @throws IOException If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public boolean ready() throws IOException { if (closed) throw new IOException("Reader closed"); Reader in = getCurrentReader(); if (in == null) return false; return in.ready(); } /** * Close the stream and any underlying streams. * Once a stream has been closed, further read(), ready(), mark(), or reset() * invocations will throw an IOException. Closing a previously-closed stream, * however, has no effect. * * @throws IOException If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public void close() throws IOException { if (closed) return; for (Reader reader: readerQueue) { reader.close(); } closed = true; } /** * Mark not supported. * * @throws IOException because mark is not supported. * * @since ostermillerutils 1.04.00 */ @Override public void mark(int readlimit) throws IOException { throw new IOException("Mark not supported"); } /** * Reset not supported. * * @throws IOException because reset is not supported. * * @since ostermillerutils 1.04.00 */ @Override public void reset() throws IOException { throw new IOException("Reset not supported"); } /** * Mark not supported. * * @return false * * @since ostermillerutils 1.04.00 */ @Override public boolean markSupported(){ return false; }
}
</source>
Read the file one buffer at a time
<source lang="java">
import java.io.FileReader; public class Main {
public static void main(String[] argv) throws Exception { FileReader fr = new FileReader("text.txt"); int count; char chrs[] = new char[80]; do { count = fr.read(chrs); for (int i = 0; i < count; i++) System.out.print(chrs[i]); } while (count != -1); }
}
</source>
Testing for end of file while reading a byte at a time
<source lang="java">
// : c12:TestEOF.java // Testing for end of file while reading a byte at a time. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class TestEOF {
// Throw exceptions to console: public static void main(String[] args) throws IOException { DataInputStream in = new DataInputStream(new BufferedInputStream( new FileInputStream("TestEOF.java"))); while (in.available() != 0) System.out.print((char) in.readByte()); }
} ///:~
</source>
This class is an part implementation of DataInput. It wraps a Reader object.
<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.DataInput; import java.io.EOFException; import java.io.IOException; import java.io.Reader; /**
* This class is an part implementation of DataInput. It wraps a Reader object. * * @author Fred Toussi (fredt@users dot sourceforge.net) * @version 1.9.0 * @since 1.9.0 */
public class ReaderDataInput implements DataInput {
protected Reader reader; protected int pos; int lastChar = -1; public ReaderDataInput(Reader reader) { this.reader = reader; this.pos = 0; } // methods that implement java.io.DataInput public final void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } public final void readFully(byte[] bytes, int off, int len) throws IOException { if (len < 0) { throw new IndexOutOfBoundsException(); } int n = 0; while (n < len) { int b = read(); if (b < 0) { throw new EOFException(); } bytes[off + n++] = (byte) b; } } public final boolean readBoolean() throws IOException { int b = read(); if (b < 0) { throw new EOFException(); } return (b != 0); } public final byte readByte() throws IOException { int b = read(); if (b < 0) { throw new EOFException(); } return (byte) b; } public final int readUnsignedByte() throws IOException { int b = read(); if (b < 0) { throw new EOFException(); } return b; } public short readShort() throws IOException { int b1 = read(); if (b1 < 0) { throw new EOFException(); } int b2 = read(); if (b2 < 0) { throw new EOFException(); } return (short) ((b1 << 8) | b2); } public final int readUnsignedShort() throws IOException { int b1 = read(); int b2 = read(); if ((b1 | b2) < 0) { throw new EOFException(); } return ((b1 << 8) + (b2)); } public final char readChar() throws IOException { int b1 = read(); int b2 = read(); if ((b1 | b2) < 0) { throw new EOFException(); } return (char) ((b1 << 8) + (b2)); } public int readInt() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public long readLong() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public final float readFloat() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public final double readDouble() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public int skipBytes(int n) throws IOException { throw new java.lang.RuntimeException("not implemented."); } public String readLine() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public String readUTF() throws IOException { throw new java.lang.RuntimeException("not implemented."); } public int read() throws IOException { if (lastChar >= 0) { int val = lastChar & 0xff; lastChar = -1; pos++; return val; } lastChar = reader.read(); if (lastChar < 0) { return lastChar; } pos++; return lastChar >> 8; }
}
</source>
Use a FileReader to display a text file.
<source lang="java">
import java.io.FileReader; public class Main {
public static void main(String[] argv) throws Exception { FileReader fr = new FileReader("text.txt"); int ch; do { ch = fr.read(); if (ch != -1) System.out.println((char) ch); } while (ch != -1); fr.close(); }
}
</source>