如果文本文件包含字符串java,则从文本文件中删除行

时间:2019-01-17 00:39:44

标签: java

我想从文本文件中读取内容,如果找到某些电子邮件,则希望删除整行。

所以我想删除email555@email.com

stuffherestuffemail555@email.comstuffstuff
otherrandomwordsinrandomorder
reandom word and spaces maybe @ and charcters email555@email.com
APPLEPEARAPPLE
CATDOGCAT
CATDOGPEARemail555@email.comDogPear

对此

otherrandomwordsinrandomorder
APPLEPEARAPPLE
CATDOGCAT

代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


class SendReq {
  public static void main(String[] args) throws FileNotFoundException, 
IOException{

    File inputFile = new File("testfile.txt");
    if (!inputFile.exists()){
        inputFile.createNewFile();
    }
    File tempFile = new File("tempfile.txt");
    if (!tempFile.exists()){
        tempFile.createNewFile();
    }
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String lineToRemove = "NAMEOFEMAIL@EMAIL.com";
    String currentLine;

    while((currentLine = reader.readLine()) != null) {
        // trim newline when comparing with lineToRemove
        String trimmedLine = currentLine.trim();
        if(trimmedLine.equals(lineToRemove)) continue;
        writer.write(currentLine + System.getProperty("line.separator"));
    }
    writer.close();
    reader.close();
    boolean successful = tempFile.renameTo(inputFile);
    System.out.println(successful);

  }
}

0 个答案:

没有答案