Handling text files in Java involves performing operations like reading from, writing to, and appending to files. Here are some common techniques and examples for handling text files in Java:
FileReader
and BufferedReader
are classes in Java used for reading text from files. Here’s a detailed explanation of each:
FileReaderFileReader
is a class in Java that is used to read character files. It is a convenient class for reading text files using the default character encoding of the operating system.
Key Points:- Purpose: To read text files.
- Inheritance: It extends
InputStreamReader
, which in turn extends Reader
. - Encoding: Uses the default character encoding of the operating system unless specified otherwise.
- Basic Usage: Suitable for simple file reading tasks.
Example:
create a text file "example.txt" using any text editor and then run this program.In this example, FileReader reads the file character by character.
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("example.txt");
int character;
while ((character = fileReader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedReaderBufferedReader
is a class that reads text from an input stream, buffering characters to provide efficient reading of characters, arrays, and lines. It can wrap around other Reader
classes, such as FileReader
, to enhance their performance.
Key Points:- Purpose: To read text efficiently by buffering input.
- Inheritance: It extends
Reader
. - Buffering: Buffers input to provide efficient reading of characters, arrays, and lines.
- Line Reading: Provides a method
readLine()
to read a line of text, which is very convenient for reading text files line by line.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing to a Text FileUsing FileWriter character by character
import java.io.FileWriter;
import java.io.IOException;
public class WriteCharacterByCharacterExample {
public static void main(String[] args) {
FileWriter fileWriter = null;
try{ // true to append, false to overwrite
fileWriter = new FileWriter("example.txt", true);
fileWriter.write('H');
fileWriter.write('e');
fileWriter.write('l');
fileWriter.write('l');
fileWriter.write('o');
fileWriter.write(',');
fileWriter.write(' ');
fileWriter.write('W');
fileWriter.write('o');
fileWriter.write('r');
fileWriter.write('l');
fileWriter.write('d');
fileWriter.write('!');
fileWriter.write('\n');
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:- FileWriter: Used to write characters to a file. The
true
parameter in the FileWriter
constructor indicates that the file should be appended to rather than overwritten. - write(char c): Writes a single character to the file.
- '\n': Writes a newline character to the file.
Using FileWriter and BufferedWriterimport java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try {
FileWriter fileWriter = new FileWriter("example.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine();
bufferedWriter.write("Welcome to file handling in Java.");
bufferedWriter.newLine();
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:FileWriter
writes characters to a file.BufferedWriter
wraps FileWriter
to provide efficient writing.newLine()
method is used to insert a new line.
Programs to tryReading a File and and write to another (copy file)
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
// Open the input file for reading
FileReader fileReader = new FileReader(inputFilePath);
bufferedReader = new BufferedReader(fileReader);
// Open the output file for writing
FileWriter fileWriter = new FileWriter(outputFilePath);
bufferedWriter = new BufferedWriter(fileWriter);
// Read from the input file and write to the output file
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
System.out.println("File read and write operation completed successfully.");
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
} finally {
// Close the BufferedReader
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedReader: " + e.getMessage());
}
}
// Close the BufferedWriter
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedWriter: " + e.getMessage());
}
}
}
}
}
Write a Java program that reads a file and displays the file on the screen, with a line number before each line.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileDisplayWithLineNumbers {
public static void main(String[] args) {
String inputFilePath = "input.txt"; // Replace with your file path
BufferedReader bufferedReader = null;
try {
// Open the input file for reading
FileReader fileReader = new FileReader(inputFilePath);
bufferedReader = new BufferedReader(fileReader);
// Read from the input file and display with line numbers
String line;
int lineNumber = 1;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(lineNumber + ": " + line);
lineNumber++;
}
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
} finally {
// Close the BufferedReader
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedReader: " + e.getMessage());
}
}
}
}
}
Program to Count Characters, Lines, and Words in a Text File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class FileStatistics {
public static void main(String[] args) {
String inputFilePath = "input.txt"; // Replace with your file path
BufferedReader bufferedReader = null;
int characterCount = 0;
int lineCount = 0;
int wordCount = 0;
try {
// Open the input file for reading
FileReader fileReader = new FileReader(inputFilePath);
bufferedReader = new BufferedReader(fileReader);
// Read from the input file
String line;
while ((line = bufferedReader.readLine()) != null) {
lineCount++;
characterCount += line.length();
// Use StringTokenizer to count words in the line
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
wordCount++;
}
}
// Display the results
System.out.println("Number of characters: " + characterCount);
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
} finally {
// Close the BufferedReader
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedReader: " + e.getMessage());
}
}
}
}
}
Java program that reads numbers from an input file, separates the odd and even numbers, and writes them into two different files: one for odd numbers and one for even numbers.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class SeparateOddEven {
public static void main(String[] args) {
String inputFilePath = "numbers.txt"; // Replace with your input file path
String oddFilePath = "odd_numbers.txt"; // File to write odd numbers
String evenFilePath = "even_numbers.txt"; // File to write even numbers
BufferedReader bufferedReader = null;
BufferedWriter oddWriter = null;
BufferedWriter evenWriter = null;
try {
// Open the input file for reading
FileReader fileReader = new FileReader(inputFilePath);
bufferedReader = new BufferedReader(fileReader);
// Open the output files for writing
FileWriter oddFileWriter = new FileWriter(oddFilePath);
FileWriter evenFileWriter = new FileWriter(evenFilePath);
oddWriter = new BufferedWriter(oddFileWriter);
evenWriter = new BufferedWriter(evenFileWriter);
// Read numbers from the input file and separate them
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split("\\s+"); // Split the line into numbers
for (String numberStr : numbers) {
try {
int number = Integer.parseInt(numberStr.trim());
if (number % 2 == 0) {
evenWriter.write(number + " ");
} else {
oddWriter.write(number + " ");
}
} catch (NumberFormatException e) {
System.err.println("Skipping invalid number: " + numberStr);
}
}
}
System.out.println("Odd and even numbers have been separated into different files.");
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
} finally {
// Close the BufferedReader
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedReader: " + e.getMessage());
}
}
// Close the BufferedWriter for odd numbers
if (oddWriter != null) {
try {
oddWriter.close();
} catch (IOException e) {
System.err.println("Failed to close oddWriter: " + e.getMessage());
}
}
// Close the BufferedWriter for even numbers
if (evenWriter != null) {
try {
evenWriter.close();
} catch (IOException e) {
System.err.println("Failed to close evenWriter: " + e.getMessage());
}
}
}
}
}
Explanation:- File Paths: The input file path (
numbers.txt
) and the output file paths for odd and even numbers (odd_numbers.txt
and even_numbers.txt
) are specified. - BufferedReader and BufferedWriter: Declared outside the try block for visibility in the finally block.
Reading and Separating Numbers:
- The program reads each line from the input file using
BufferedReader
. - Each line is split into numbers using
split("\\s+")
, which splits the line based on whitespace. - Each number is checked whether it's even or odd and written to the corresponding file.
- Exception Handling: Catches and prints any
IOException
that occurs during the file operations. - Finally Block: Ensures that the
BufferedReader
and BufferedWriter
are closed, even if an exception occurs.
Comments
Post a Comment