Extended TextToHTML (files) Learn programming Java

Lesson:

File Management


Exercise:

Extended TextToHTML (files)


Objetive:

Expand the TextToHtml class, so that ir can dump it result to a text file. Create a method ToFile, which will receive the name of the file as a parameter.

Hint: You must use a "StreamWriter"


Code:

public class TextToHTML
{
	private String[] html;
	private int lines;
	private int count;

	public TextToHTML()
	{
		count = 0;
		lines = 1000;

		html = new String[lines];
	}

	public final void ToFile(String nameFile)
	{
		try
		{
			java.io.FileWriter file = new java.io.FileWriter(nameFile);
			file.write(toString() + System.lineSeparator());
			file.close();
		}
		catch (RuntimeException e)
		{
			System.out.println("Error!!!");
		}
	}

	public final void Add(String line)
	{
		if (count < lines)
		{
			html[count] = line;
			count++;
		}
	}

	public final String toString()
	{
		String textHtml;

		textHtml = "\n";
		textHtml += "\n";

		for (int i = 0; i < count; i++)
		{
			textHtml += "";
			textHtml += html[i];
			textHtml += "\n";
		}

		textHtml += "\n";
		textHtml += "\n";

		return textHtml;
	}


	public final void Display()
	{
		System.out.print(toString());
	}

}

public class Main
{
	public static void main(String[] args)
	{
		TextToHTML textToHTML = new TextToHTML();
		textToHTML.Add("Hello");
		textToHTML.Add("How are you?");
		textToHTML.Display();
		textToHTML.ToFile("prueba.html");
	}
}

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