CSC419 ยท 2081 ยท 5 marks
Assume that a text file named 'ONE.TXT' contains a paragraph of text. Write a program to copy the word that starts with vowel from 'ONE.TXT' to another file 'TWO.TXT'.
Assume that a text file named 'ONE.TXT' contains a paragraph of text. Write a program to copy the word that starts with vowel from 'ONE.TXT' to another file 'TWO.TXT'. [5]
Advanced Java ProgrammingChapter 1: Programming in JavaWorking with Files
Copying Words Starting with Vowels from ONE.TXT to TWO.TXT
Approach
- Read the content of
ONE.TXTword by word - Check if each word starts with a vowel (a, e, i, o, u -- both uppercase and lowercase)
- If yes, write that word to
TWO.TXT
Java Program
import java.io.*;
public class CopyVowelWords {
public static void main(String[] args) {
// Declare file reader and writer references
BufferedReader br = null;
BufferedWriter bw = null;
try {
// Open ONE.TXT for reading
br = new BufferedReader(new FileReader("ONE.TXT"));
// Open TWO.TXT for writing
bw = new BufferedWriter(new FileWriter("TWO.TXT"));
String line;
// Read file line by line
while ((line = br.readLine()) != null) {
// Split each line into words by spaces/punctuation
String[] words = line.split("[\\s.,;:!?]+");
for (String word : words) {
// Check if word is non-empty
if (word.length() > 0) {
// Get the first character of the word
char firstChar = word.charAt(0);
// Check if first character is a vowel
if (firstChar == 'a' || firstChar == 'e' ||
firstChar == 'i' || firstChar == 'o' ||
firstChar == 'u' || firstChar == 'A' ||
firstChar == 'E' || firstChar == 'I' ||
firstChar == 'O' || firstChar == 'U') {
// Write the vowel-starting word to TWO.TXT
bw.write(word);
bw.newLine();
}
}
}
}
System.out.println("Words starting with vowels copied to TWO.TXT successfully.");
} catch (FileNotFoundException e) {
System.out.println("File ONE.TXT not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO Error occurred: " + e.getMessage());
} finally {
// Close streams in finally block to ensure they always close
try {
if (br != null) br.close();
if (bw != null) bw.close();
} catch (IOException e) {
System.out.println("Error closing files: " + e.getMessage());
}
}
}
}
Sample Input (ONE.TXT)
An apple is a fruit. Orange and mango are tasty.
Every student enjoys learning.
Sample Output (TWO.TXT)
An
apple
is
a
Orange
and
are
Every
enjoys
Key Points
| Concept | Detail |
|---|---|
FileReader | Reads characters from ONE.TXT |
BufferedReader | Reads line by line efficiently |
FileWriter | Writes characters to TWO.TXT |
BufferedWriter | Writes output efficiently |
split("[\\s.,;:!?]+") | Splits line into individual words |
charAt(0) | Gets the first character of each word |
finally block | Ensures streams are always closed |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.