How to Java programming- Create a File & Write in it

Java.io package provides classes for system input and output through data streams, serialization, and the file system. IOException is a class of Exception that was raised due to all Input/Output contingencies. The file operations like read(), write() and close() etc. are OS dependent and are declared as native methods. The java.io.File.createNewFile() method atomically creates a new file named by this abstract pathname. This method is used to create a file in Java, and return a boolean value: true if the file is created successfully; false if the file already exists or the operation failed.

 

1.Create a File using file.createNewFile.

Below is a java code demonstrates the use of createNewFile() method of File class.

Create 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();
		}
		}
	}

 

On the first run of above example, the file has been created successfully while on the second run it failed. That is because the file is already created on the first run.

 

2.Create a File and write in it using PrintWriter.

The Java PrintWriter class java.io.PrintWriter enables you to write formatted data to an underlying Writer. For instance, writing int, long and other primitive data formatted as text, rather than as their byte values.

Create File and Write
	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) {
				e.printStackTrace();
			}
		}

	}

 

This example first creates a PrintWriter instance which is connected to a FileWriter. Then it writes a boolean, an int and a float to the PrintWriter. Third, the example calls the advanced println() method of the PrintWriter which can insert formatted numbers into a text string. At last, the PrintWriter is closed.

 

Demo

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...