I have a file abc.txt that has lines as
Ethernet 1/1
Ethernet 1/2
interface 3
abs_mod_
jjj
kkkk
ll
abs_mod_
interface 6
interface 7
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();
}
}
}