Below is a simple Java program that reads a file, searches for a line containing “new H1”, and replaces it with a new line.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class ReplaceLineInFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt"; // Replace with your file path
String searchString = "new H1";
String replacementString = "new H1 Replacement";
try {
replaceLine(filePath, searchString, replacementString);
System.out.println("Line replaced successfully!");
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
public static void replaceLine(String filePath, String searchString, String replacementString) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
StringBuilder content = new StringBuilder();
// Read the file content and replace the line
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchString)) {
content.append(replacementString).append(System.lineSeparator());
} else {
content.append(line).append(System.lineSeparator());
}
}
reader.close();
// Write the modified content back to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(content.toString());
writer.close();
}
}
Replace the filePath variable with the path to your actual file. The program reads the file, searches for a line containing “new H1”, replaces it with the specified replacementString, and writes the modified content back to the file.
This program is generated by ChatGPT. Read more articles on the topic of AI on my blog: https://programtom.com/dev/category/software-development/chatgpt/
