StackTips

How to Create a Text File in Java

nilan avtar

Written by

Nilanchala,  1 min read,  2.71K views, updated on Sept. 17, 2023

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();
		}

	}
}

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!