How to remove a line from a file in java?

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

package com.kodehelp.javaio;
 
import java.io.*;
 
/**
 *
 * Date: 10/3/11
 */
public class RemoveALine {
    publicstatic 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(newFileReader("/conf.ini"));
            PrintWriter pw =new PrintWriter(newFileWriter(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();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值