skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Friday, September 14, 2012

Repalce Word from the Given File Java Example

Posted by Admin at 2:00 PM – 0 comments
 

If we pass a file path and a word and the replace word to a method then it will replace all the word in that file with replace word.


/************************
 * Code to replace all word in a test file 
 ************************/
import java.io.*;

public class repalceWord {
        /*Repalces words in a file*/
 
 public static void contentReplace(String filepath,String word,String replaceword) {
  //String filepath="D:/test.txt";
  //String word="something";
  //String replaceword="evertthing";
  String data="";
  File file=new File(filepath);
  try{
                    
      FileInputStream fis = new FileInputStream(file);/*creates a new file input stream */
                    
      InputStreamReader is = new InputStreamReader(fis);/*Creates a new file input stream*/
                    
      BufferedReader br = new BufferedReader(is);/*creates a buffer reader*/
      String strLine="";
                    
      while ((strLine = br.readLine()) != null)/*checks if their are any lines in a file
           {
                                
        if(strLine.contains(word)){ /*checks if the file contains such a word*/
                                         
         data+=strLine.replaceAll(word, replaceword)+"n";/*It replaces all the words in the file*/
        }else{
                                        
         data+=strLine+"n";/*If no such word it moves to next line*/
        }
           }
      System.out.println(data);
      br.close();
      is.close();
   fis.close();
   FileOutputStream fileOutputStream=new FileOutputStream(filepath,false);/*creates a new file output stream */
   Writer outx=new OutputStreamWriter(fileOutputStream);/*creates a Writer for the file output stream */
    
   if(data.contains("n")){ 
    String[] list=data.split("n");/*split the data*/
    for(int i=0;i<list.length;i++){
     
     outx.write(list[i]);
     outx.append("n");
     
    } 
   }else{
    outx.write(data);
    outx.append("n");
   }
   outx.close();
   fileOutputStream.close();
      
  }catch(Exception e){
   e.printStackTrace();
  }
  
 }
}

Labels: Java File Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger