Home Tutorial Java Core Files Java file create new file

 
 

Java file create new file
Posted on: April 14, 2006 at 12:00 AM
Advertisement
This section demonstrates you how to create a new file.

Java file create new file

This section demonstrates you how to create a new file.

Description of code:

Manipulating a file is a common task in programming. Java makes this easy by providing many useful tools. Through the use of these tools, you can can easily create a new empty file. Now for this task, we have used the method createNewFile() of boolean type which creates a new empty file if and only if a file with this name does not yet exist.

createNewFile(): This method of File class creates an empty file at the specified file location if a file with this name does not exist.

exists(): This method of File class checks whether the given file exists or not.

Here is the code:

import java.io.*;

public class FileCreate {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/newfile.txt");
		if (file.exists()) {
			System.out.println("File already exists");
		} else {
			file.createNewFile();
			System.out.println("File is created");
		}
	}
}

Through the method createNewFile(), you can create a file.

Output:

File is created
Advertisement

Related Tags for Java file create new file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com