Java Examples – How to create a file in Java




Java Tutorial for Beginners
Java Tutorial for Beginners

File.createNewFile() Method can be used to Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. File.createNewFile() Method returns true if the named file does not exist and was successfully created; false if the named file already exists.

Below is the example to create a file in java.

//package com.codebind.file;
import java.io.File;
import java.io.IOException;

public class CreateFileClass 
{
    public static void main( String[] args )
    {	
    	try {
    		 
	      File file = new File("C:\\fileName.txt");
	      
	      if (file.createNewFile()){
	        System.out.println("New File is created!");
	      }else{
	        System.out.println("File with the same name already exists.");
	      }
	      
    	} catch (IOException e) {
	      e.printStackTrace();
	}
    }
}

Java Examples – Create a File and Write in it Using PrintWriter and File class

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

public class Demo {

	public static void main(String[] args) {

		try {
		File file = new File("fileName1.txt");
        
		if(!file.exists()) {
				file.createNewFile();	
		}
		
		PrintWriter pw = new PrintWriter(file);
		pw.println("this is my file content");
		pw.println(100000);
		pw.close();
		System.out.println("Done");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*