Wednesday, January 12, 2011

FileCopying

File copying while copying replace the required string with another string charecters
/**
*
* @author Madarapu Naveen
*/

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

public class FileCopy {

/**
* @param args
*/
  public static void main(String args[]) throws IOException {
   String str1 = "mr..";
   String str2 = "ra";

   FileInputStream fin = new FileInputStream("myfile");

   int ch;
   StringBuilder input = new StringBuilder();
   while ((ch = fin.read()) != -1) {
   input.append((char) ch);
   }
   fin.close();
   System.out.println(input.toString());

   StringTokenizer tokens = new StringTokenizer(input.toString(), " ");
   System.out.println("test");
   StringBuilder sbuff = new StringBuilder();
   while (tokens.hasMoreTokens()) {
    String st = tokens.nextToken();
    if (st.equals(str1)) {
     StringBuilder lbuff = new StringBuilder();
     if (str1.length() == str2.length()) {
      st = str2;
      sbuff.append(st);
     } else {
      if (str1.length() > str2.length()) {

       char c = 0;
       for (int i = 0; i < str2.length(); i++) {
        if (i == str2.length() - 1) {
         lbuff.append(str2.charAt(i));
         c = str2.charAt(i);
        } else {
         lbuff.append(str2.charAt(i));
        }
       }
       System.out.println(c);
       while (lbuff.length() < str1.length()) {
        lbuff.append(c);
       }
      }
     }
     sbuff.append(lbuff.toString());
     sbuff.append(" ");
    } else {
     sbuff.append(st);
     sbuff.append(" ");
    }

   }

   String finalContent = sbuff.toString();
   FileWriter fout = new FileWriter("file2.txt");

   for (int i = 0; i < finalContent.length(); i++) {

    fout.write(finalContent.charAt(i));
   }
   fin.close();
   fout.close();
 }
}

No comments:

Post a Comment