- java.lang.Object
-
- spice.basic.TextReader
-
public class TextReader extends java.lang.Object
Class TextReader provides a simple interface for reading text files sequentially.Code Examples
1) The following program writes a small text file, then reads and prints all lines of the file.import java.io.*; import spice.basic.*; // // Create a new text file, write to it, then // read back what was written. The name of the // file is supplied on the command line. // class TextIOEx1 { // // Load the JNISpice shared library. // static { System.loadLibrary( "JNISpice" ); } public static void main ( String[] args ) throws SpiceException { // // Create a small text file. // final int NLINES = 10; String fname = args[0]; TextWriter tw = new TextWriter( fname ); for ( int i = 0; i < NLINES; i++ ) { String line = "This is line " + i + " of the text file."; tw.writeLine( line ); } // // Close the TextWriter. // tw.close(); // // Now read the text file and print each line as we // read it. // TextReader tr = new TextReader( fname ); String line = tr.getLine(); while( line != null ) { System.out.println( line ); line = tr.getLine(); } // // Close the TextReader. // tr.close(); } }
The program can be executed using the command
java TextWriterEx1 ex1.txt
When run on a PC/Linux/java 1.6.0_14/gcc platform, the output from this program was a file named "ex1.txt" containing the text:
This is line 0 of the text file. This is line 1 of the text file. This is line 2 of the text file. This is line 3 of the text file. This is line 4 of the text file. This is line 5 of the text file. This is line 6 of the text file. This is line 7 of the text file. This is line 8 of the text file. This is line 9 of the text file.
Version 1.0.0 21-DEC-2009 (NJB)
-
-
Field Summary
Fields Modifier and Type Field Description private java.lang.String
fname
private java.io.BufferedReader
inputStream
-
Constructor Summary
Constructors Constructor Description TextReader(java.lang.String fname)
Create a TextReader for a text file specified by name.
-
-
-
Constructor Detail
-
TextReader
public TextReader(java.lang.String fname) throws SpiceException
Create a TextReader for a text file specified by name.- Parameters:
fname
-- Throws:
SpiceException
-
-
Method Detail
-
getLine
public java.lang.String getLine() throws SpiceException
Read the next line from the text file associated with this TextReader instance.A null return value indicates the end of file.
This method closes the underlying input stream if end-of-file is reached or if an exception is thrown.
- Returns:
- Throws:
SpiceException
-
close
public void close() throws SpiceException
Close a TextReader instance.This method allows the caller to close the underlying input stream in situations where it would not automatically be closed. Compare
getLine()
above.- Throws:
SpiceException
-
-