Skip to content

How to create new file in java

Ramesh Fadatare edited this page Jul 17, 2018 · 5 revisions

file.createNewFile() method Overview

java.io.File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java.

File createNewFile() method returns true if new file is created and false if file already exists. This method also throws java.io.IOException when it’s not able to create the file. The files created is empty and of zero bytes.

Create File Example

package com.javaguides.javaio.fileoperations.fileexamples;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CreateFileExample {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CreateFileExample.class);
	
	public static void main(String[] args) {
		createFile();
	}
	
	public static void createFile() {
		File file = new File("C:/workspace/java-io-guide/sample.txt");
		try {
			if (file.createNewFile()) {
				LOGGER.info("File is created !!");
			} else {
				LOGGER.info("File is already exist");
			}
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
	}
}

Reference

https://docs.oracle.com/javase/8/docs/api/java/io/File.html

Clone this wiki locally