How to create a file in java.

How to create a file in java.


Posted in : Core Java Posted on : October 21, 2010 at 1:15 PM Comments : [ 0 ]

Here, you will see how to create a file in existing directory in java.

How to create a file in java.

In this example, you will see how to create a new file in java. There is a class FileDemo that has method createFile(). In this method, first of all we will creates a object of file. The exists() method of File class check the availability of  this file. If file already present then it generate an exception and if not exist then the createNewFile() method of File class create new file of given name.

Code:
CreateAFile.java
import java.io.File;
import java.io.IOException;

class FileDemo {
	public void createFile() {
		File file = new File("CreateFile.txt");
		try {
			if (!file.exists()) {
				file.createNewFile();
				System.out.println("File created.");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
public class CreateAFile {
	public static void main(String[] arg) {
		FileDemo fileDemo = new FileDemo();
		fileDemo.createFile();
	}
}
Output:
C:\>java CreateAFile
File created.

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics