To convert all capital letters to small letters in a “.txt “file using Java involves reading the file, converting the text to lowercase, and then writing the modified text back to the file or to a new file.
Conversion of all the capital letters in a .txt file to small letters
The following are the steps required to convert capital letters in a “.txt” file to lower case in java,
1.Reading the File: Use “FileReader” and “BufferedReader” to read the content of the file. These classes provide efficient reading of characters, arrays and lines.
2.Converting Text: Convert the text to lowercase using the “toLowerCase()” method of the “String” class. This method returns a new string with all characters converted to lowercase.
3.Writing to the file: Use “FileWriter” and “BufferedWriter” to write the modified content back to the file or to a new file. These classes provide efficient writing of characters, arrays and strings
Implementation:
import java.io.*;
public class ConvertToLowercase {
public static void main(String[] args) {
String inputFilePath = "input.text";
String outputFilePath = "output.text";
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(inputFilePath));
writer = new BufferedWriter(new FileWriter(outputFilePath));
String line;
while ((line = reader.readLine()) != null) {
String lowerCaseLine = line.toLowerCase();
writer.write(lowerCaseLine);
writer.newLine();
}
System.out.println("File conversion completed successfully.");
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
System.err.println("An error occurred while closing resources: " + e.getMessage());
}
}
}
}
Key points:
- File paths : Define the paths for the input and output files. You can change ‘input.txt’ and ‘output.txt‘ to the actual file names or paths you are using
- BufferedReader and BufferedWriter : These are used for efficient reading and writing.
- Reading and Converting : The program reads each line from the input file, converts it to lowercase using ‘tolowerCase()’, and then writes the converted line to the output file.
- Error Handling : The program includes error handling to catch and display any ‘IOException’ that might occur during file operations.
- Resource Management : The ‘finally’ block ensures that resources are properly closed, even if an error occurs.
Input and Output:
Assume the input as:
Hello Buddy! THIS is a Task. java programming LANGUAGE.
The Output looks as:
hello buddy! this is a task. java programming language.