How to convert HTML to Javascript (.js) in Java
For some security reasons, you may need to convert your HTML file into Javascript (js) file, and display the JS file instead of the HTML file directly. The concept is quite simple – using the document.write
HTML
<h1>Convert HTML to Javascript file</h1>
Javascript (js)
document.write('<h1>Convert HTML to Javascript file</h1>');
1. Test.html
Create a simple HTML file, convert this file to Javascript later.
Convert HTML to Javascript file
2. ConvertHTMLToJs.java
Create a Java class to convert all the HTML code into a Javascript (.js) file.
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.PrintStream;
public class ConvertHTMLToJs {
private static final String FOLDER = "c:\\";
private static final String JS_FILE_NAME = "output.js";
private static final String HTML_FINE_NAME = "test.html";
private static final String JS_PREFIX = "document.write('";
private static final String JS_SUFIX = "');";
public static void main(String[] args) {
try {
//read html file
BufferedReader br = new BufferedReader(new FileReader(FOLDER + File.separator + HTML_FINE_NAME));
//output it to js file
OutputStream os= new FileOutputStream(new File(FOLDER + File.separator + JS_FILE_NAME));
PrintStream ps = new PrintStream(os);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine())!= null) {
line = sb.append(JS_PREFIX).append(line).append(JS_SUFIX).toString();
//clear the StringBuffer content
sb.delete(0, sb.length());
ps.println(line);
}
ps.close();
os.close();
br.close();
System.out.println("done");
}catch(Exception e) {
e.printStackTrace();
}
}
}
3. Output.js
Run the above Java program, it will convert “Test.html” to “Output.js”
document.write('<html>');
document.write('<body>');
document.write('<h1>Convert HTML to Javascript file</h1>');
document.write('</body>');
document.write('</html>');
4. Test It
Create a HTML file and include the “Output.js” file for display.
Test-js.html
You will notice both “Test.html” and “Test-js.html” are display the same content, but with different methods to display it.
I have copied the file ConvertHTMLToJs . when I com[piel with java class file is created but is nor running
I tried and got zero results. let me know if you wish to see the html