How to remove a line from a file in java?

By October 3, 2011 at 11:27 pm · java.io

Below java code shows how to remove a line from a file

/****************************************************************************************
 * Created on 10-2011Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.*;

/**
 * Created by http://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("Parameter is not an existing file");
                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();
        }
    }
}
email

DeeKay has been working in Java, JEE and opensource technology since 7 years and has same years of experience in software development. His area of interest is TDD, Scala langauge, Java, JEE techologies.

Related Posts

Popular Posts