Take the 2-minute tour ×

I have to check a text doc whether it exists or not and then i have to replace a letter in that say a to o. I have done the first part how to replace char

class FDExists{
  public static void main(String args[]){
    File file=new File("trial.java");
    boolean exists = file.exists();
    if (!exists) {

      System.out.println("the file or directory you are searching does not exist : " + exists);


      System.out.println("the file or directory you are searching does exist : " + exists);

This i have done

share|improve this question
Do you want to replace the a by o into the file ? Or in the filename ? –  Colin Hebert Oct 15 '10 at 9:31
inside file. I mean in the data –  Sumithra Oct 15 '10 at 9:34

1 Answer 1

You cannot do that in one line of code.

You have to read the file (with an InputStream), modify the content, and write it in the file (with an OutputStream).

Example code. I omitted try/catch/finally blocks for a better comprehension of the algorithm but in a real code, you have to add theses blocks with a correct gestion of resources liberation. You can also replace "\n" by the system line separator, and replace "a" and "o" by parameters.

public void replaceInFile(File file) throws IOException {

    File tempFile = File.createTempFile("buffer", ".tmp");
    FileWriter fw = new FileWriter(tempFile);

    Reader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    while(br.ready()) {
        fw.write(br.readLine().replaceAll("a", "o") + "\n");


    // Finally replace the original file.
share|improve this answer

Your Answer


