Saturday, October 18, 2008

How to modify the contents of file?

When we went to replace the specific information in the file. This method will help.

public void modifyFile(String filePath, String textToFind,String textToReplace) {
PrintWriter outputStream = null;
try {
File tmpFile = new File(filePath);
String newText = readAndReplace(tmpFile, textToFind, textToReplace);
outputStream = new PrintWriter(new FileWriter(tmpFile));
outputStream.print(newText);
outputStream.flush();
} catch (IOException ioe) {
// handle exception here
} catch (Exception ioe) {
// handle exception here
} finally {
if (outputStream != null) {
outputStream.close();
}
}

}

private String readAndReplace(File file, String textToFind,String textToReplace) throws Exception {
StringBuffer sb = new StringBuffer();
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(file));
String line = "";
while ((line = inputStream.readLine()) != null) {
if (line.contains(textToFind)) {
line = line.replace(textToFind, textToReplace);
}
sb.append(line);
}
} catch (IOException ioe) {
// handle exception
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
inputStream = null;
}

return sb.toString();
}

No comments: