Android Text File Replace replaceAFileText(String fileName, String word, String replaceWord)

Here you can find the source of replaceAFileText(String fileName, String word, String replaceWord)

Description

Replace a File text for a new one.

Parameter

Parameter Description
fileName a parameter
word a parameter
replaceWord a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void replaceAFileText(String fileName, String word,
        String replaceWord) throws IOException 

Method Source Code

//package com.java2s;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    /**/*from w  ww. ja  va 2 s  .  co m*/
     * Replace a File text for a new one.
     * 
     * <p> Created at:  22/11/2013  </p>
     *
     * @param fileName
     * @param word
     * @param replaceWord
     * @throws IOException
     */
    public static void replaceAFileText(String fileName, String word,
            String replaceWord) throws IOException {

        String tempFileName = fileName + "_temp";

        BufferedWriter writer = new BufferedWriter(new FileWriter(
                tempFileName));
        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String linha;
        while ((linha = reader.readLine()) != null) {
            if (linha.contains(word)) {
                linha = linha.replace(word, replaceWord);
            }
            writer.write(linha + "\n");
        }

        writer.close();
        reader.close();

        new File(fileName).delete();
        new File(tempFileName).renameTo(new File(fileName));
    }
}