How to Create Text File using Java Program

Create Text File using Java

In this example, I am attaching Simple program about, How to Create Text File using Java. The example program has been tested and shared in the post.

CreateTxtFile.java

package com.dineshkrish;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CreateTxtFile {

	// You can change the path accordingly
	private static final String DESTINATION_PATH = "output/";
	
	private static final String FILE_EXTENSION = ".txt";
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("Enter the file name ?");
		String fileName = scanner.next(); // Reading File name from user
		
		String path = DESTINATION_PATH + fileName + FILE_EXTENSION;
		
		File file = new File(path);
		
		boolean status = false;
		
		try {
			
			// Creating the File
			status = file.createNewFile();
			
		} catch (IOException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		if(status) {
			
			System.out.println("The file is created successfully...");
		} else {
			
			System.out.println("Can not able to create file...");
		}
		
		scanner.close();
		
	}
}

Output

Enter the file name ?
dineshkrishnan
The file is created successfully…

Generated File

Create Text File using Java

References

1. java.io API JavaDocs
2. java.io.File API JavaDocs