Example 1: Java Program to Create a File
// importing the File class
import java.io.File;
class Main {
public static void main(String[] args) {
// create a file object for the current location
File file = new File("JavaFile.java");
try {
// create a new file with name specified
// by the file object
boolean value = file.createNewFile();
if (value) {
System.out.println("New Java File is created.");
}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have created a file object named file. The file object is linked with the specified path.
// javaFile.java is equivalent to
// currentdirectory/JavaFile.java
File file = new File("JavaFile.java");
We then use the createNewFile()
method of the File
class to create new file to the specified path.
Note: If the file JavaFile.java is not already present, then only the new file is created. Otherwise the program returns The file already exists.
Example 2: Java Program to Write Content to the File
In Java, we can use the FileWriter
class to write data to a file. In the previous example, we have created the file named JavaFile.java. Now let's write a program to the file.
// importing the FileWriter class
import java.io.FileWriter;
class Main {
public static void main(String args[]) {
// creates a multiline string using + operator
// the string is a Java Program
String program = "class JavaFile { " +
"public static void main(String[] args) { " +
"System.out.println(\"This is file\");"+
"}"+
"}";
try {
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("JavaFile.java");
// Writes the program to file
output.write(program);
System.out.println("Data is written to the file.");
// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have used the FileWriter
lass to write the string data to the file Javafile.java.
When you run the program, the file JavaFile.java
will includes the data present in the string program.