Tutorials Java How to Create a Text File in Java

How to Create a Text File in Java

In this article we will see how to create a text file in java. In this example, we’ll use the PrintWriter class.

package com.javatechig;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class CreateTextFile {

	public static void main(String[] args) {
		PrintWriter writer = null;
		try {
			/* Create a new file with UTF-8 encoding */
			writer = new PrintWriter("file1.txt", "UTF-8");

			/* Write content to file */
			writer.println("Hello, this is a binary file.");
			writer.println("Put your file contents here...");

			writer.close();			
			System.out.println("New File Created!");			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}
}
Total
0
Shares
Leave a Reply

Your email address will not be published.

Previous Post
Java Design Pattern Tutorials

Singleton Design Pattern in Java

Next Post
Java Tutorials

Copying the Contents of One text file to Another in Java

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All