Cannot write to created HTML file in Java
You need to ensure the file is closed. Use try-with-resources as in:
File f = new File(path + index + ".html");
try (FileWriter fw = new FileWriter(f)) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContent);
break;
} catch (Exception e) {
index++;
}
Note that the (essentially) empty catch
block will hide any exceptions from you. Not a good idea.
Also, while(true)
and break
are unnecessary.
Building HTML in Java code only
There can be several approaches.
First you can use String, or StringBuilder. This is good for extremely short HTMLs like <html>Hello, <b>world</b></html>
.
If HTML is more complicated it is easier to use some API. Take a look on these links:
http://xerces.apache.org/xerces-j/apiDocs/org/apache/html/dom/HTMLBuilder.html
Java HTML Builder (anti-template) library?
or search html builder java
in google.
Other possibility is templating. If you actually have a template where you wish to replace a couple of words you can write your HTML as an *.html
file with {0}
, {}
marks for parameters. Then just use java.text.MessageFormat
to create actual HTML text.
The next approach is to use "real" template engine like Velocity.
Java server send html page from file to browser
As you test your server with a web browser, you need to send a valid HTTP request including HTTP headers which are provided in your hardcoded part.
So, you should just add output of the header part just before you print the contents of the file.
Also you need to collect the information about the file size, and send "Content-Length: " + file_size + "\r\n"
header.
There's a bug with closing printWriter before you finish reading the page file, you need to close it after the loop:
while(line != null)//repeat till the file is empty
{
printWriter.println(line);//print current line
printWriter.flush();// I have also tried putting this outside the while loop right before
printWriter.close() // BUG: no ";" and closing printWriter too early
line = reader.readLine();//read next line
}
So, updated method to send your file to the client is as follows:
private void sendPage(Socket client) throws Exception {
System.out.println("Page writter called");
File index = new File("index.html");
PrintWriter printWriter = new PrintWriter(client.getOutputStream());// Make a writer for the output stream to
// the client
BufferedReader reader = new BufferedReader(new FileReader(index));// grab a file and put it into the buffer
// print HTTP headers
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html");
printWriter.println("Content-Length: " + index.length());
printWriter.println("\r\n");
String line = reader.readLine();// line to go line by line from file
while (line != null)// repeat till the file is read
{
printWriter.println(line);// print current line
line = reader.readLine();// read next line
}
reader.close();// close the reader
printWriter.close();
}
How to Open HTML file using Java?
I would prefer to use default browser
File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());
Related Topics
How to Get the Methodinfo of a Java 8 Method Reference
Navigation Drawer Closes on Click
Android:Java.Lang.Outofmemoryerror:
How to Read Firestore Sub-Collection and Pass It to Firestorerecycleroptions
Difference Between Actionbarsherlock and Actionbar Compatibility
Android - Prevent White Screen at Startup
How to Generate a Qr Code for an Android Application
How to Give an Imageview Click Effect Like a Button on Android
Using File.Listfiles with Filenameextensionfilter
Why Doesn't Java Throw an Exception When Dividing by 0.0
Calculate Elapsed Time in Java/Groovy
Custom JSON Deserialization with Jackson
Using Custom Font in Android Textview Using Xml
How to Set Menu to Toolbar in Android
How to Create Your Own Library for Android Development to Be Used in Every Program You Write