We are moved to new domain
Click -> www.ehowtonow.com
Tuesday, 12 May 2015

How to Create File using Java

Following example shows hoe to create file using File() constructor and file.createNewFile() method in Java

createNewFile
public boolean createNewFile() throws
Atomically creates a new, empty file named by this abstract pathname if
and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Returns:
true if the named file does not exist and was successfully created; false if the named file already exists.
Throws:
IOException - If an I/O error occurred.
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file.

Sample Program
CreateFile.java
package com.javatutorialcorner.file;

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

public class CreateFile {

 public static void main(String[] args) {
  String path = "/home/annamalai/workspace/File/jtc.txt";
  try {
   File jtcFile = new File(path);
   if (!jtcFile.exists()) {
    jtcFile.createNewFile();
    System.out.println("File Created Successfully!");
   } else {
    System.out.println("Error, file already exists.");
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }

 }

}


Result
The above code will create new file if file not exist in specified directory.
File Created Successfully!

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to Create File using Java Rating: 5 Reviewed By: eHowToNow