Saturday, June 16, 2012

Java IO : Create a new file

Creating a new file in Java using the File.createNewFile() method.

Reference : http://docs.oracle.com/javase/6/docs/api/java/io/File.html#createNewFile()

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

public class CreateNewFile {
    public static void main(String[] args) {
        try {

            File file = new File("c:\\sample.txt");

            //true if the named file does not exist and was successfully created;
            // false if the named file already exists
            boolean res = file.createNewFile();

            if (res) {
                System.out.println("File is successfully created!");
            } else {
                System.out.println("File already exists.");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment