Below java code shows how to remove specific line or lines from a file
/****************************************************************************************
* Created on 10-2011Copyright(c) https://kodehelp.com All Rights Reserved.
****************************************************************************************/
package com.kodehelp.javaio;
import java.io.*;
/**
* Created by https://kodehelp.com
* Date: 10/3/11
*/
public class RemoveALine {
public static void main(String args[]){
try {
File inputFile = new File("/conf.ini");
if (!inputFile.isFile()) {
System.out.println("File does not exist");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inputFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader("/conf.ini"));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals("REMOVE THIS LINE")) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
References: