TXT to HTML translator Learn programming Java

Lesson:

File Management


Exercise:

TXT to HTML translator


Objetive:

Create a "Text to HTML converter", which will read a source text file and create a HTML file from its contents. For example, if the file contains:

Hola
Soy yo
Ya he terminado

The name of the destination file must be the same as the source file, but with ".html" extension (which will replace the original ".txt" extension, if it exists). The "title" in the "head" must be taken from the file name.


Code:

package TXTtoHTML;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		System.out.print("Enter name of file: ");
		String nameFileTxt = new Scanner(System.in).nextLine();
		String nameFileHtml = nameFileTxt.substring(0, nameFileTxt.length() - 4);

		if ((new java.io.File(nameFileTxt)).isFile())
		{
			java.io.FileReader myfileTxt;
		java.io.BufferedReader myfileTxtBufferedReader = new java.io.BufferedReader(myfileTxt);
			java.io.FileWriter myfileHtml;

			myfileTxt = new java.io.FileReader(nameFileTxt);
			myfileHtml = new java.io.FileWriter(nameFileHtml + ".html");
			String line;

			myfileHtml.write("" + System.lineSeparator());
			myfileHtml.write("" + System.lineSeparator());
			myfileHtml.write(nameFileHtml + System.lineSeparator());
			myfileHtml.write("" + System.lineSeparator());
			myfileHtml.write("" + System.lineSeparator());
			do
			{
				line = myfileTxtBufferedReader.readLine();
				if (line != null)
				{
					myfileHtml.write("" + line + "" + System.lineSeparator());
				}
			} while (line != null);

			myfileHtml.write("" + System.lineSeparator());
			myfileHtml.write("" + System.lineSeparator());

			myfileTxt.close();
			myfileHtml.close();
		}
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.