How To Read And Write Text File In Java
Maybe your like
- Home>
- Java SE>
- File I/O
| Learn Java File IO: | |
|
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.
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.
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");That creates a new reader with the Unicode character encoding 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);And for a BufferedWriter example:OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8"); BufferedWriter bufWriter = new BufferedWriter(writer);Now, let’s look at some complete examples.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(); } } }The following example reads a text file with assumption that the encoding is UTF-16: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.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(); } } }This program writes some Unicode string (Vietnamese) to the specified text file.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) { e.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 - Common File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to execute Operating System Commands in Java
- 3 ways 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 extract ZIP file in Java
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.| [Java source code] | 4 kB |
Add comment
Notify me of follow-up comments
SendCancelComments
12345#25Arnav2022-01-11 17:39Thanks for explaining the read and write assignment in detailQuote#24Vamsh2021-07-15 23:36codejava.net/.../...Quote#23Ravindu2020-12-10 11:04Thank you so much.. I summited my assignment using your blog. this is a great work....Quote#22D2020-03-20 14:29Brilliant article! Thanks for the help!Quote#21Vladan M. Kostic2019-09-11 05:05Hi, this is nice document for developers.It's important to point out that there are also Java APIs that allow developers to be creat and edit MS Word, Excel or ODF filesfrom Java codeHave you tried the Java API component of the Independent company?There are a number of use cases on the site and the API itself is well documented.Quote12345Refresh comments listTag » How To Read The Text File In Java
-
Different Ways Of Reading A Text File In Java - GeeksforGeeks
-
Java Read Files - W3Schools
-
Reading A Plain Text File In Java - Stack Overflow
-
Java Read Text File - DigitalOcean
-
How To Read A File In Java - Baeldung
-
Java: Read Text File Easily - YouTube
-
Different Ways Of Reading A Text File In Java
-
Reading A Text File In Java - Tutorialspoint
-
Read From Text File In Java - SyntaxDB - Java Syntax Reference
-
How To Read A Text File In Java - Home And Learn Courses
-
How To Read A Text File In Java - Coding Game
-
Reading A Text File In Java - Quick Programming Tips
-
How To Read A Text File As String In Java? Example - Java67
-
How To Read A File In Java