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 fileif(!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"))returnfalse;
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))returntrue;returnfalse;}
/* 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);}}