Reverse Words in a Text File in Java

Write a program using StringTokenizer to read all the sentences stored in a text file “content.txt”, extract each word and then display the reverse of each word in separate lines.

import java.io.*;
import java.util.StringTokenizer;
class Reverse{
    public static void main(String args[])throws IOException{
        FileReader fr = new FileReader("content.txt");
        BufferedReader br = new BufferedReader(fr);
        String line = new String();
        while((line = br.readLine()) != null){
            StringTokenizer st = new StringTokenizer(line, " .?!,");
            int count = st.countTokens();
            for(int i = 1; i <= count; i++){
                String word = st.nextToken();
                StringBuffer sb = new StringBuffer(word);
                sb.reverse();
                System.out.println(sb);
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.