Here you can find the source of replaceAFileText(String fileName, String word, String replaceWord)
Parameter | Description |
---|---|
fileName | a parameter |
word | a parameter |
replaceWord | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static void replaceAFileText(String fileName, String word, String replaceWord) throws IOException
//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)); } }