Assembly How to Read Characters From a File
- Details
- Written by
- Terminal Updated on 28 July 2019 | Impress Electronic mail
In this tutorial, we show you lot how to read from and write to text (or grapheme) files using classes available in the coffee.io parcel. First, let'southward look at the dissimilar 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.
- shut() : closes the stream.
InputStreamReader is a span from byte streams to character streams. Information technology converts bytes into characters using a specified charset. The charset can be default graphic symbol encoding of the operating organization, or can be specified explicitly when creating an InputStreamReader .
FileReader is a user-friendly class for reading text files using the default grapheme 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 user-friendly method for reading a line of text readLine() .
The following diagram show relationship of these reader classes in the coffee.io packet:
two. Author, OutputStreamWriter, FileWriter and BufferedWriter
Writer is the abstract class for writing graphic symbol streams. It implements the following key methods:
- write(int) : writes a unmarried character.
- write(char[]) : writes an array of characters.
- write(String) : writes a string.
- close() : closes the stream.
OutputStreamWriter is a bridge from byte streams to character streams. Characters are encoded into bytes using a specified charset. The charset can exist default character encoding of the operating system, or can be specified explicitly when creating an OutputStreamWriter .
FileWriter is a user-friendly class for writing text files using the default grapheme encoding of the operating arrangement.
BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are buffered to avert ofttimes writing to the underlying stream) and provides a user-friendly method for writing a line separator: newLine() .
The following diagram prove relationship of these author classes in the java.io parcel:
3. Character Encoding and Charset
When constructing a reader or author object, the default character encoding of the operating system is used (due east.g. Cp1252 on Windows):
FileReader reader = new FileReader("MyFile.txt"); FileWriter author = new FileWriter("YourFile.txt"); So if we want to apply a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:
InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16"); That creates a new reader with the Unicode grapheme encoding UTF-xvi.
And the post-obit statement constructs a writer with the UTF-8 encoding:
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8"); In case we desire to use a BufferedReader , simply wrap the InputStreamReader inside, for example:
InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16"); BufferedReader bufReader = new BufferedReader(reader); And for a BufferedWriter example:
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8"); BufferedWriter bufWriter = new BufferedWriter(author); At present, let's look at some complete examples.
4. Java Reading from Text File Example
The following small program reads every single grapheme from the file MyFile.txt and prints all the characters to the output console:
packet net.codejava.io; import java.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file. * @writer world wide web.codejava.cyberspace * */ public class TextFileReadingExample1 { public static void principal(String[] args) { effort { FileReader reader = new FileReader("MyFile.txt"); int grapheme; while ((grapheme = reader.read()) != -1) { Arrangement.out.print((char) grapheme); } reader.close(); } take hold of (IOException e) { due east.printStackTrace(); } } } The following example reads a text file with assumption that the encoding is UTF-xvi:
package net.codejava.io; import coffee.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 world wide web.codejava.internet * */ 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()) != -i) { Arrangement.out.print((char) grapheme); } reader.close(); } take hold of (IOException e) { e.printStackTrace(); } } } And the post-obit case uses a BufferedReader to read a text file line by line (this is the almost efficient and preferred manner):
bundle net.codejava.io; import java.io.BufferedReader; import coffee.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file * using a BufferedReader for efficiency. * @author world wide web.codejava.cyberspace * */ public class TextFileReadingExample3 { public static void principal(String[] args) { attempt { FileReader reader = new FileReader("MyFile.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != aught) { Organization.out.println(line); } reader.close(); } take hold of (IOException e) { east.printStackTrace(); } } }5. Java Writing to Text File Example
In the post-obit example, a FileWriter is used to write 2 words "Hello Earth" and "Practiced Bye!" to a file named MyFile.txt:
package internet.codejava.io; import coffee.io.FileWriter; import java.io.IOException; /** * This programme demonstrates how to write characters to a text file. * @writer world wide web.codejava.net * */ public grade TextFileWritingExample1 { public static void master(String[] args) { try { FileWriter writer = new FileWriter("MyFile.txt", true); writer.write("Howdy World"); writer.write("\r\due north"); // write new line writer.write("Adept Bye!"); writer.close(); } take hold of (IOException eastward) { eastward.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 lot want to suspend text to an existing file, pass a boolean flag of truthful to constructor of the author class:
FileWriter writer = new FileWriter("MyFile.txt", truthful); The following example uses a BufferedReader that wraps a FileReader to suspend text to an existing file:
bundle 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) { endeavour { FileWriter writer = new FileWriter("MyFile.txt", true); BufferedWriter bufferedWriter = new BufferedWriter(author); bufferedWriter.write("Hi Earth"); bufferedWriter.newLine(); bufferedWriter.write("See Yous Again!"); bufferedWriter.close(); } take hold of (IOException due east) { e.printStackTrace(); } } } This is the preferred mode to write to text file considering the BufferedReader provides efficient way for writing character streams.
And the post-obit example specifies specific character encoding (UTF-16) when writing to the file:
package net.codejava.io; import java.io.BufferedWriter; import coffee.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /** * This plan demonstrates how to write characters to a text file using * a specified charset. * @writer www.codejava.net * */ public class TextFileWritingExample3 { public static void master(Cord[] args) { try { FileOutputStream outputStream = new FileOutputStream("MyFile.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-xvi"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write("Xin chào"); bufferedWriter.newLine(); bufferedWriter.write("Hẹn gặp lại!"); bufferedWriter.close(); } catch (IOException due east) { e.printStackTrace(); } } } This plan writes some Unicode string (Vietnamese) to the specified text file.
NOTE: From Coffee vii, you tin can use endeavor-with-resources argument to simplify the lawmaking of opening and closing the reader/writer. For instance:
try (FileReader reader = new FileReader("MyFile.txt")) { int character; while ((character = reader.read()) != -1) { Organisation.out.impress((char) character); } } catch (IOException east) { eastward.printStackTrace(); }References:
- Lesson: Bones I/O (The Java Tutorials)
Related File IO Tutorials:
- How to Read and Write Binary Files in Coffee
- How to read text file line by line in Coffee
- Java IO FileReader and FileWriter Examples
Other Java File IO Tutorials:
- How to list files and directories in a directory in Java
- Java IO - Mutual File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Coffee Externalization with Examples
- How to execute Operating System Commands in Coffee
- iii means for reading user's input from console in Java
- File change notification example with Watch Service API
- Java Scanner Tutorial and Code Examples
- How to compress files in ZIP format in Java
- How to excerpt Goose egg file in Java
Nearly the Author:
Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Coffee in the time of Coffee ane.4 and has been falling in love with Java since then. Make friend with him on Facebook and lookout man his Java videos you YouTube.
Add comment
Source: https://www.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-java
0 Response to "Assembly How to Read Characters From a File"
Post a Comment