Answer:
// here is code in java.
import java.io.*;
import java.util.Scanner;
class Main{
// function to check a word is palindrome or not
private static boolean is_Palind(String str1)
{
// if length of String is 0 or 1
if(str1.length() == 0 || str1.length() == 1)
{
return true;
}
else
{
// recursively check the word is palindrome or not
if(str1.charAt(0) == str1.charAt(str1.length()-1))
{
return is_Palind(str1.substring(1,str1.length()-1));
}
else
{
return false;
}
}
}
// driver function
public static void main(String[] args)
{// variable to store word
String word;
// BufferedWriter object
BufferedWriter buff_w = null;
// FileWriter object
FileWriter file_w = null;
// Scanner object
Scanner sc = null;
try
{
// read the input file name
sc = new Scanner(new File("input.txt"));
// output file
file_w = new FileWriter("output.txt");
// create a buffer in output file
buff_w = new BufferedWriter(file_w);
// read each word of input file
while(sc.hasNext())
{
word = sc.next();
// check word is palindrome or not
if(is_Palind(word))
{
// if word is palindrome then write it in the output file
buff_w.write(word);
buff_w.write("\n");
}
}
// close the buffer
buff_w.close();
// close the input file
sc.close();
}
// if there is any file missing
catch (FileNotFoundException e) {
System.out.println("not able to read file:");
}
// catch other Exception
catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
Create a scanner class object to read the word from "input.txt" file.Read a word from input file and check if it is palindrome or not with the help of is_Palind() function.it will recursively check whether string is palindrome or not. If it is palindrome then it will written in the output.txt file with the help of BufferedWriter object. This will continue for all the word of input file.
Input.txt
hello world madam
level welcome
rotor redder
output.txt
madam
level
rotor
redder