In this section we will be showing an example java source code that enable us to create a new file. As you are already aware of a computer file is a block of arbitrary information. It is somehow a resource to store information in digital format. It is a modern version of paper documents stored in our offices and libraries. In java creating a new file is an easy task. Below is a sample source code that creates a new file using java.
package com.javatutorialhq.tutorial; import java.io.File; import java.io.IOException; public class CreateFile { /** * This java sample code shows how create a new file * Property of * javatutorialhq.com * All Rights Reserved * Version 1.0 05/18/2012 */ public static void main(String[] args) { File f = new File("C:\\temp\\test.txt"); if(f.exists()){ System.out.println("File already exists"); } else{ try { f.createNewFile(); System.out.println("File "+f.getPath()+" was created"); } catch (IOException e) { e.printStackTrace(); } } } }
On the first run the following output was produced:
File C:\temp\test.txt was created
However if you attempt to run again the java program that creates a new file, the following output was produced:
File already exists
The filename C:\temp\test.txt was passed along the File constructor. And the method createNewFile() was exposed in creating a blank file with a filename declared on the constructor of the File class. The method exists() was also available in order to check if the file intended to create exists or not thus the second run of this java program result in message File already exists. One notable method that we used as well is the getPath(). This method converts the abstract path name as declared on the file constructor into a pathname string. The resulting string uses the default name separator character to separate the names in the name sequence.[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]