编程语言
首页 > 编程语言> > 【Java】file操作-删除文件中某一行中符合某一规则的

【Java】file操作-删除文件中某一行中符合某一规则的

作者:互联网

效果

此处规则,删除已空格分隔的域名行,为防止因制表符等引起误删,强制插入的规则空格分隔 
同时要过滤掉# 和其他非自己插入的数据格式,避免误删

在这里插入图片描述

代码

package com.ths.arsenaldnsnginxconfig.test;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.File;

import java.io.FileWriter;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.PrintWriter;

public class FileUtil {
    public void removeLineFromFile(String file, String lineToRemove) {
        try {
            File inFile = new File(file);
            if (!inFile.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(inFile.getAbsolutePath() + ".tmp");
            BufferedReader br = new BufferedReader(new FileReader(file));
            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 (!findRealmName(line, lineToRemove)) {
                    pw.println(line);
                    pw.flush();
                }
            }

            pw.close();
            br.close();

//Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

//Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();

        }

    }

    /**
     * 查找完全匹配的域名
     */
    private boolean findRealmName(String line, String s){
        System.out.println("当前行情况"+line);
        if (line.contains("\t")) {
            System.out.println("当前行有制表符");
        }
        if (line.contains("#") || line.trim().isEmpty() || !line.contains(" ") || line.contains("\t"))
            return false;
        String[] sArr = line.trim().split(" ");
        System.out.println("切割到的空格后字符串"+ sArr[1]);
        String realmName = sArr[1].substring(0, sArr[1].lastIndexOf('.'));
        System.out.println("匹配到的字符串" + realmName);
        if (s.equals(realmName))
            return true;
        return false;
    }




    public static void main(String[] args) {
        FileUtil util = new FileUtil();

        util.removeLineFromFile("D:/about/dns/test.txt", "hub.cn");

    }

}

标签:Java,String,System,某一,file,println,new,line
来源: https://blog.csdn.net/weixin_43469680/article/details/120781982