How to Update HTML Header section with new code in JAVA

2.1k Views Asked by At

I have few htmls where i want to Replace Header Section with my new Lines of code. ( My new code is - new CSS, new JS file imports and few scripts ).

I want to replace all existing Header section and to replace with new one. This changes should be permanent.

I know how to do it in JS or Jquery but it is not feasible as it will execute each time when html will load.

If i get a solution in java like i will run particular backend code only once and it updates my HTML file permanently.

<html>
<head>
    <script>Existing</script>
    <link rel="stylesheet" src="existing.css"/>
    <script type="text/javascript" src="existing.js"/>
</head>
</html>

To Replace with AND

I also want to Add NEW few Div tag structures in Body tag in my updated HTML file.

   <html>
        <head>
            <script>New Script code</script>
            <link rel="stylesheet" src="newCSS.css"/>
            <script type="text/javascript" src="newJavaScript.js"/>
        </head>
        <body>
                      <div>Hi Welcome</div>
                      <div>
                              <p>Paragraphs</p>
                      </div>
        </body>
     </html>

Please help. :)

1

There are 1 best solutions below

5
On

You can use a library like jsoup to modify the HTML and write the changed HTML to the same file.

Something like this:

try {
    File file = new File("index.html");
    Document doc = Jsoup.parse(file, "UTF-8");
    // clear the <head> element and add a new <script> element.
    doc.head().html("").appendElement("script")
            .attr("type", "text/javascript")
            .attr("src", "newScript.js");
    //write the changed HTML to the same file.
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
        bw.write(doc.html());
    }
} catch (IOException e) {
    e.printStackTrace();
}