javafilefile-writingfileupdate

Search and Replace a content in a file in JAVA


I have to edit the contents of a file and write the edited conted to another file.Here is the code iam using .

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

public class TestRef {     
    ArrayList<String> lines = new ArrayList<String>();     
    String line= null;     
    public void printThis(){     
        try{     
    FileReader fr = new FileReader("C:\\Users\\questions.txt");     
    BufferedReader br = new BufferedReader(fr);     
    FileWriter fw = new FileWriter("C:\\Users\\questions_out.txt");     
    BufferedWriter out = new BufferedWriter(fw);     
    while((line=br.readLine()) != null) {  
     if(line.contains("Javascript"))
      line.replace("Javascript"," JAVA");          
        lines.add(line);     
        out.write(line);  
        }                    

        }     
    catch(Exception e){}     
    }     

    public static void main(String [] args){     
            TestRef tr = new TestRef();     
            tr.printThis();     
        }     
} 

So this is like reading one line at a time and printing it back to the file. But when I execute this code the output file is blank.? Can you please provide me with a sample code, how to read from a file, make change in the content and write the whole file to a new file ?


Solution

  • Well, a few problems:

    The first one is the most likely cause of your current problem, but the rest should help when you're past that. (The point about "replace" will probably be your next issue...)