How to delete the specific lines that starts and ends with specific string in a file in java?

后端 未结 2 601
眼角桃花
眼角桃花 2021-01-17 02:47

I have a file abc.txt that has lines as

abc.txt

Ethernet 1/1 

Ethernet 1/2

interface 3

abs_mod_
jjj
kkkk
ll
abs_mod_

interface 6

interface 7
         


        
2条回答
  •  一生所求
    2021-01-17 03:15

    A naive approach:

    package test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadStringFromFileLineByLine {
    
        public static void main(String[] args) {
            try {
                File file = new File("abc.txt");
                FileReader fileReader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                boolean flag = true;
                while ((line = bufferedReader.readLine()) != null) {
                    if(line.contains("abs_mod_")){
                        if(flag)    flag = false;
                        else        flag = true;
                    }else if(flag){
                        stringBuffer.append(line);
                        stringBuffer.append("\n");
                    }
                }
                fileReader.close();
                System.out.println("Contents of file:");
                System.out.println(stringBuffer.toString().replace("\n\n\n", "\n\n"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    Using regex:

    package test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadStringFromFileLineByLine {
    
        public static void main(String[] args) {
            try {
                File file = new File("abc.txt");
                FileReader fileReader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                    stringBuffer.append("\n");
                }
                fileReader.close();
                System.out.println("Contents of file:");
                System.out.println(
                    stringBuffer
                    .toString()
                    .trim()
                    .replaceAll("[\\n]+(abs_mod_)(\\s|\\S)*(abs_mod_)", "")
                );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题