效果
此处规则,删除已空格分隔的域名行,为防止因制表符等引起误删,强制插入的规则空格分隔
同时要过滤掉# 和其他非自己插入的数据格式,避免误删
![在这里插入图片描述](https://img-blog.csdnimg.cn/c8acc5ddc5214921b952be219c3b7d48.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA55GeIOaWsA==,size_20,color_FFFFFF,t_70,g_se,x_16)
代码
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;
import java.util.StringTokenizer;
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().replaceAll(" +", " ").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");
}
*/
public static void main(String[] args) {
// 考虑删除此类异常情况多空格,空格数量不定
String str = " abc def ghi mnopq r s ";
// 法1
// StringTokenizer pas = new StringTokenizer(str, " ");
// str = ""; //这里清空了str,但StringTokenizer对象中已经保留了原来字符串的内容。
//
// while (pas.hasMoreTokens()) {
// String s = pas.nextToken();
// str = str + s + " ";
// }
// System.out.println(str.trim());
// 法2
String s = str.trim().replaceAll(" +", " ");
System.out.println(s);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)