Pages

Thursday, December 6, 2012

Anagram words in text file and file write and replace text through java

Hi all,

Before few days I was having an assignment which need to apply Anagram to the words in a given text file through java. No way of using predefined methods or algorithms for this. Therefore I created simple java program to do this. This might also help you to understand about anagram and some techniques of applying anagram through java.

This is the source code.....

Just imagine that the existing file name is "test"

import java.io.*;
import java.util.StringTokenizer;
 

public class FileRead {

    static String sentence [];
    static String temp [];
    static int i = 0;
    static String first="";

 public static void Read() {

  try{

  // Read the existing text file

  FileInputStream fstream = new FileInputStream("test.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  

  String strLine;
 

  while ((strLine = br.readLine()) != null) {

     StringTokenizer stk = new StringTokenizer(strLine);
     sentence = new String[stk.countTokens()];
    temp = new String[sentence.length];
    while(stk.hasMoreTokens()) {
    sentence[i] = stk.nextToken();
    i++;

  }

  for(int x=0;x<sentence.length;x++){

if(x==0){
temp[x]= sentence[(sentence.length-1)];
}
else{
temp[x]= sentence[x-1];

}

  }
  for(int x=0;x<temp.length;x++){
     first=first+temp[x]+" ";

  }
  // Print original sentence
  System.out.println (strLine);
  System.out.println ("\n");
  System.out.println ("Apply anagram for the above sentence.");
  //Print Anagramed sentence.
  System.out.print (first+"\n");

  first="";

You can write this new phrase by using Filewritter and Bufferwritter as below mentioned. I'm using new text file to write new phrase......


// Write Anagramed sentence to new text file
File file =new File("test1.txt");
    //if file doesnt exists, then create it
    if(!file.exists()){
    file.createNewFile();
    }
    FileWriter fileWritter = new FileWriter(file.getName(),false);
    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    bufferWritter.write(first);


The statement "FileWriter fileWritter = new FileWriter(file.getName(),false);" includes "false" in the end of the statement. We can use true instead of using false. The different of these two is , we can write new word or phrase right after the existing word or phrase in the text file by using "true". When we use "false" it will replace the existing word or phrase by given word or phrase.

1 comment:

  1. Words containing "Hao"

    There are Total 8 words containing this word. List of all words Containing Hao are listed below categorized upon number of words.

    Example : Chaotic, Chaoses

    ReplyDelete