This is the second solution to find all the strings with no vowels, in a given file. This approach uses the FileReader, Scanner, StringTokenizer, and Pattern class of Java regular expressions.
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class WordsWithoutVowels {
public static void main(String[] args) throws IOException {
/* Display the current sampleFile.txt file contents */
displayFileContent("C:\\Users\\Nagendra\\sampleFile.txt");
/* Re-open the same sampleFile.txt file using Scanner and
FileReader, to search for a given word in each line of this file */
FileReader fileRead=new FileReader("C:\\Users\\Nagendra\\sampleFile.txt");
@SuppressWarnings("resource")
Scanner scanFile = new Scanner(fileRead);
System.out.println();
/* Read line by line and search for a word with no vowels in
* each line of sampleFile.txt file using the StringBuffer methods.
* Call the function parseEachLine() */
System.out.println("The list of words with no vowels existing in the given file");
while (scanFile.hasNextLine())
parseEachLine(scanFile.nextLine());
}
private static void parseEachLine(String lineRd){
StringTokenizer strTokens=new StringTokenizer(lineRd);
while (strTokens.hasMoreElements()) {
String eachToken=(String) strTokens.nextElement();
/*Using the below regular expression, scan each word
* in the line and check whether the pattern of
* zero Vowels exists with any number of consonants.
*/
if (Pattern.matches("[^aeiouAEIOU]*", eachToken))
System.out.println(eachToken);
}
}
private static void displayFileContent(String filePath) throws IOException {
/* Display the sample file contents to the console using the
Scanner and FileReader */
FileReader fRead=new FileReader(filePath);
Scanner scanFile = new Scanner(fRead);
System.out.println("The contents of the file are below");
System.out.println("----------------------------------");
while (scanFile.hasNextLine())
System.out.println(scanFile.nextLine());
scanFile.close();
}
}
OUTPUT:
The contents of the old file are below
----------------------------------
This is the reason why I like Java language.
Sky is the limit for Java language features.
Hence Java language is in my learning list.
Many people are liking Java language since two decades.
The list of words with no vowels existing in the given file
why
Sky
my

Leave a comment