How to create file java

How to create file java

To create file in java you can use java.io.File class and its method createNewFile(). Below java class shows how to create file in local directory using java. You could also choose your network folder to create file with proper permission and access. In below java program first it will create directory in C:\ drive then create file in it.

package com.javahonk.transienttest;

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

public class CreateFileUsingJava {

    public static void main(String[] args) {

	try {

	    File createDirectory = new File("C:\\JavaHonk");
	    // Create directory first
	    boolean directoyCreated = createDirectory.mkdir();
	    if (directoyCreated) {
		System.out.println("Directory created!");
	    } else {
		System.out.println("Its is already exists");
	    }

	    // create new file if not exits
	    File file = new File("C:\\JavaHonk\\Test.txt");

	    if (file.createNewFile()) {
		System.out.println("File created!");
	    } else {
		System.out.println("File exists");
	    }

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

}

 

Output:

How to create file java

That’s it for How to create file java .

Leave a Reply

Your email address will not be published. Required fields are marked *