Reading and Writing Text File
Reading and writing text files in Java can be achieved using BufferedReader
and BufferedWriter
for efficient text operations, as well as Scanner
for convenient input processing. Below are detailed explanations and examples for each method:
1. Reading Text Files Using BufferedReader
:
In this example, BufferedReader
is used to read text data line by line from the "input.txt" file. The readLine()
method reads a line of text. The try-with-resources
statement ensures that each resource is closed at the end of the statement.
2. Writing Text Files Using BufferedWriter
:
In this example, BufferedWriter
is used to write text data to the "output.txt" file. The write(String)
method writes a string to the output stream.
3. Reading Text Files Using Scanner
:
In this example, Scanner
is used to read text data line by line from the "input.txt" file. The hasNextLine()
method checks if there is another line in the file, and nextLine()
method reads the next line.
4. Writing Text Files Using BufferedWriter
and User Input (Scanner):
In this example, Scanner
is used to read user input from the console, and the input is written to the "output.txt" file using BufferedWriter
. The program continues to take input until the user types "exit".
Explanation:
Using
BufferedReader
andBufferedWriter
:BufferedReader
is used for efficient reading of text from a character-input stream, such as a file.BufferedWriter
is used for efficient writing of text to a character-output stream, such as a file.
Using
Scanner
:Scanner
is a versatile class that can be used to read user input from the console or text from a file.
Remember to handle exceptions properly to ensure your file operations are robust and can handle any potential issues that may arise during reading and writing.
Last updated