Share on Google+Share on Google+

Java file create new file

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

Advertisements

Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.