Writing to a text file Learn programming Java

Lesson:

File Management


Exercise:

Writing to a text file 12


Objetive:

Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt"


Code:

package FileWrite;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		String sentence = " ";
		java.io.FileWriter myfile;
		myfile = new java.io.FileWriter("test.txt");
		do
		{
			System.out.print("Enter a sentence: ");
			sentence = new Scanner(System.in).nextLine();
			if (sentence.length() != 0)
			{
				myfile.write(sentence + System.lineSeparator());
			}
		} while (sentence.length() != 0);
		myfile.close();
	}
}