gpt4 book ai didi

java - 如何删除java文件中以特定字符串开头和结尾的特定行?

转载 作者:行者123 更新时间:2023-12-02 09:53:22 25 4
gpt4 key购买 nike

我有一个文件 abc.txt,其行为

abc.txt

Ethernet 1/1 

Ethernet 1/2

interface 3

abs_mod_
jjj
kkkk
ll
abs_mod_

interface 6

interface 7

我想删除abs_mod_之间的行以及以abs_mod_开头的行

最终输出应该是

abc.txt

Ethernet 1/1

Ethernet 1/2

interface 3

interface 6

interface 7

我尝试过如何逐行读取文件。

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());
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

一种幼稚的方法:

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();
}
}
}

使用正则表达式:

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();
}
}
}

关于java - 如何删除java文件中以特定字符串开头和结尾的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56154994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com