tags:

views:

44

answers:

1

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);

    }else{

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

This i have done

+1  A: 

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");
    }

    fw.close();
    br.close();
    fr.close();

    // Finally replace the original file.
    tempFile.renameTo(file);
}
Benoit Courtine