Java How to Read From Text File
- Details
- Written past
- Last Updated on 28 July 2019 | Print Email
In this tutorial, we evidence you how to read from and write to text (or character) files using classes available in the java.io bundle. Offset, allow's await at the dissimilar classes that are capable of reading and writing character streams.
ane. Reader, InputStreamReader, FileReader and BufferedReader
Reader is the abstruse class for reading character streams. It implements the following primal methods:
- read() : reads a unmarried character.
- read(char[]) : reads an assortment of characters.
- skip(long) : skips some characters.
- close() : closes the stream.
InputStreamReader is a bridge from byte streams to grapheme streams. It converts bytes into characters using a specified charset. The charset can be default character encoding of the operating system, or tin can be specified explicitly when creating an InputStreamReader .
FileReader is a user-friendly grade for reading text files using the default grapheme encoding of the operating organization.
BufferedReader reads text from a character stream with efficiency (characters are buffered to avoid often 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:
2. Writer, OutputStreamWriter, FileWriter and BufferedWriter
Writer is the abstract class for writing character streams. Information technology implements the following fundamental methods:
- write(int) : writes a single grapheme.
- write(char[]) : writes an array of characters.
- write(Cord) : writes a string.
- shut() : 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 tin exist specified explicitly when creating an OutputStreamWriter .
FileWriter is a convenient form for writing text files using the default character encoding of the operating organisation.
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 user-friendly method for writing a line separator: newLine() .
The following diagram show relationship of these writer classes in the coffee.io package:
3. Character Encoding and Charset
When amalgam a reader or writer object, the default grapheme encoding of the operating system is used (east.m. Cp1252 on Windows):
FileReader reader = new FileReader("MyFile.txt"); FileWriter author = new FileWriter("YourFile.txt");
Then if we want to use a specific charset, employ an InputStreamReader or OutputStreamWriter instead. For example:
InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-sixteen");
That creates a new reader with the Unicode grapheme encoding UTF-16.
And the post-obit statement constructs a author with the UTF-8 encoding:
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-eight");
In example we desire to use a BufferedReader , just wrap the InputStreamReader inside, for case:
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(writer);
Now, permit's look at some complete examples.
4. Java Reading from Text File Example
The following pocket-size plan reads every single grapheme from the file MyFile.txt and prints all the characters to the output console:
package internet.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 grade TextFileReadingExample1 { public static void main(String[] args) { try { FileReader reader = new FileReader("MyFile.txt"); int character; while ((character = reader.read()) != -1) { System.out.impress((char) grapheme); } reader.close(); } take hold of (IOException east) { e.printStackTrace(); } } }
The post-obit instance reads a text file with assumption that the encoding is UTF-sixteen:
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 principal(Cord[] args) { endeavor { FileInputStream inputStream = new FileInputStream("MyFile.txt"); InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16"); int character; while ((character = reader.read()) != -ane) { System.out.impress((char) graphic symbol); } reader.shut(); } catch (IOException e) { e.printStackTrace(); } } }
And the post-obit example uses a BufferedReader to read a text file line by line (this is the about efficient and preferred way):
parcel net.codejava.io; import coffee.io.BufferedReader; import java.io.FileReader; import coffee.io.IOException; /** * This program demonstrates how to read characters from a text file * using a BufferedReader for efficiency. * @author www.codejava.cyberspace * */ public grade TextFileReadingExample3 { public static void chief(Cord[] args) { effort { FileReader reader = new FileReader("MyFile.txt"); BufferedReader bufferedReader = new BufferedReader(reader); Cord line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } reader.shut(); } catch (IOException eastward) { due east.printStackTrace(); } } }
v. Java Writing to Text File Example
In the following case, a FileWriter is used to write ii words "Hi Earth" and "Skillful Bye!" to a file named MyFile.txt:
package cyberspace.codejava.io; import java.io.FileWriter; import coffee.io.IOException; /** * This program demonstrates how to write characters to a text file. * @writer www.codejava.internet * */ public grade 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 author.write("Good Bye!"); writer.close(); } take hold of (IOException east) { e.printStackTrace(); } } }
Note that, a writer uses default character encoding of the operating system by default. It also creates a new file if non exits, or overwrites the existing 1. If you want to append text to an existing file, laissez passer a boolean flag of truthful to constructor of the writer class:
FileWriter author = new FileWriter("MyFile.txt", true);
The post-obit 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 coffee.io.IOException; /** * This program demonstrates how to write characters to a text file * using a BufferedReader for efficiency. * @author world wide web.codejava.net * */ public form TextFileWritingExample2 { public static void main(String[] args) { endeavor { FileWriter writer = new FileWriter("MyFile.txt", truthful); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("How-do-you-do World"); bufferedWriter.newLine(); bufferedWriter.write("Meet You Once again!"); bufferedWriter.close(); } catch (IOException east) { e.printStackTrace(); } } }
This is the preferred mode to write to text file because the BufferedReader provides efficient fashion for writing grapheme streams.
And the following example specifies specific character encoding (UTF-16) when writing to the file:
bundle net.codejava.io; import java.io.BufferedWriter; import java.io.FileOutputStream; import coffee.io.IOException; import coffee.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(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 programme writes some Unicode string (Vietnamese) to the specified text file.
NOTE: From Java 7, you lot can use try-with-resources statement to simplify the code of opening and closing the reader/writer. For example:
endeavour (FileReader reader = new FileReader("MyFile.txt")) { int grapheme; while ((graphic symbol = reader.read()) != -1) { Arrangement.out.print((char) character); } } grab (IOException e) { eastward.printStackTrace(); }
References:
- Lesson: Basic I/O (The Java Tutorials)
Related File IO Tutorials:
- How to Read and Write Binary Files in Java
- How to read text file line by line in Java
- 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 Java Externalization with Examples
- How to execute Operating Arrangement Commands in Java
- iii ways for reading user's input from panel in Java
- File modify notification case with Watch Service API
- Java Scanner Tutorial and Code Examples
- How to compress files in Null format in Java
- How to excerpt Nada file in Coffee
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Coffee ane.4 and has been falling in love with Coffee since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add together comment
Source: https://www.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-java
Post a Comment for "Java How to Read From Text File"