Reading in characters in java

How to Read and Write Text File in Java

In this tutorial, we show you how to read from and write to text (or character) files using classes available in the java.io package. First, let’s look at the different classes that are capable of reading and writing character streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading character streams. It implements the following fundamental methods:

  • read() : reads a single character.
  • read(char[]) : reads an array of characters.
  • skip(long) : skips some characters.
  • close() : closes the stream.

FileReader is a convenient class for reading text files using the default character encoding of the operating system.

BufferedReader reads text from a character stream with efficiency (characters are buffered to avoid frequently reading from the underlying stream) and provides a convenient method for reading a line of text readLine() .

The following diagram show relationship of these reader classes in the java.io package:

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract class for writing character streams. It implements the following fundamental methods:

  • write(int) : writes a single character.
  • write(char[]) : writes an array of characters.
  • write(String) : writes a string.
  • close() : closes the stream.

FileWriter is a convenient class for writing text files using the default character encoding of the operating system.

BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are buffered to avoid frequently writing to the underlying stream) and provides a convenient method for writing a line separator: newLine() .

The following diagram show relationship of these writer classes in the java.io package:

Writer Hierarchy

3. Character Encoding and Charset

When constructing a reader or writer object, the default character encoding of the operating system is used (e.g. Cp1252 on Windows):

FileReader reader = new FileReader("MyFile.txt"); FileWriter writer = new FileWriter("YourFile.txt");

So if we want to use a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:

InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16");

And the following statement constructs a writer with the UTF-8 encoding:

OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8");

In case we want to use a BufferedReader , just wrap the InputStreamReader inside, for example:

InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16"); BufferedReader bufReader = new BufferedReader(reader);
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8"); BufferedWriter bufWriter = new BufferedWriter(writer);

4. Java Reading from Text File Example

The following small program reads every single character from the file MyFile.txt and prints all the characters to the output console:

package net.codejava.io; import java.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file. * @author www.codejava.net * */ public class TextFileReadingExample1 < public static void main(String[] args) < try < FileReader reader = new FileReader("MyFile.txt"); int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >
package net.codejava.io; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * This program demonstrates how to read characters from a text file using * a specified charset. * @author www.codejava.net * */ public class TextFileReadingExample2 < public static void main(String[] args) < try < FileInputStream inputStream = new FileInputStream("MyFile.txt"); InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16"); int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >

And the following example uses a BufferedReader to read a text file line by line (this is the most efficient and preferred way):

package net.codejava.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file * using a BufferedReader for efficiency. * @author www.codejava.net * */ public class TextFileReadingExample3 < public static void main(String[] args) < try < FileReader reader = new FileReader("MyFile.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >

5. Java Writing to Text File Example

In the following example, a FileWriter is used to write two words “Hello World” and “Good Bye!” to a file named MyFile.txt :

package net.codejava.io; import java.io.FileWriter; import java.io.IOException; /** * This program demonstrates how to write characters to a text file. * @author www.codejava.net * */ public class TextFileWritingExample1 < public static void main(String[] args) < try < FileWriter writer = new FileWriter("MyFile.txt", true); writer.write("Hello World"); writer.write("\r\n"); // write new line writer.write("Good Bye!"); writer.close(); >catch (IOException e) < e.printStackTrace(); >> >

Note that, a writer uses default character encoding of the operating system by default. It also creates a new file if not exits, or overwrites the existing one. If you want to append text to an existing file, pass a boolean flag of true to constructor of the writer class:

FileWriter writer = new FileWriter("MyFile.txt", true);

The following example uses a BufferedReader that wraps a FileReader to append text to an existing file:

package net.codejava.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * This program demonstrates how to write characters to a text file * using a BufferedReader for efficiency. * @author www.codejava.net * */ public class TextFileWritingExample2 < public static void main(String[] args) < try < FileWriter writer = new FileWriter("MyFile.txt", true); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Hello World"); bufferedWriter.newLine(); bufferedWriter.write("See You Again!"); bufferedWriter.close(); >catch (IOException e) < e.printStackTrace(); >> >

This is the preferred way to write to text file because the BufferedReader provides efficient way for writing character streams.

Читайте также:  Index php page category

And the following example specifies specific character encoding (UTF-16) when writing to the file:

package net.codejava.io; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /** * This program demonstrates how to write characters to a text file using * a specified charset. * @author www.codejava.net * */ public class TextFileWritingExample3 < public static void main(String[] args) < try < FileOutputStream outputStream = new FileOutputStream("MyFile.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-16"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write("Xin chào"); bufferedWriter.newLine(); bufferedWriter.write("Hẹn gặp lại!"); bufferedWriter.close(); >catch (IOException e) < e.printStackTrace(); >> >

NOTE: From Java 7, you can use try-with-resources statement to simplify the code of opening and closing the reader/writer. For example:

try (FileReader reader = new FileReader(«MyFile.txt»)) < int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >> catch (IOException e)

References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Reading in characters in java

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

BufferedReader in = new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

Читайте также:  Java язык программирования высокого уровня

Field Summary

Fields declared in class java.io.Reader

Constructor Summary

Method Summary

Methods declared in class java.io.Reader

Methods declared in class java.lang.Object

Constructor Detail

BufferedReader

BufferedReader

Method Detail

read

read

  • The specified number of characters have been read,
  • The read method of the underlying stream returns -1 , indicating end-of-file, or
  • The ready method of the underlying stream returns false , indicating that further input requests would block.

Subclasses of this class are encouraged, but not required, to attempt to read as many characters as possible in the same fashion.

Ordinarily this method takes characters from this stream’s character buffer, filling it from the underlying stream as necessary. If, however, the buffer is empty, the mark is not valid, and the requested length is at least as large as the buffer, then this method will read characters directly from the underlying stream into the given array. Thus redundant BufferedReader s will not copy data unnecessarily.

readLine

public String readLine() throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).

skip

ready

Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.

markSupported

public boolean markSupported()

mark

Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.

reset

lines

Returns a Stream , the elements of which are lines read from this BufferedReader . The Stream is lazily populated, i.e., read only occurs during the terminal stream operation. The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined. After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line. If an IOException is thrown when accessing the underlying BufferedReader , it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place. This method will return a Stream if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.

Читайте также:  Kudel ru calc php

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью