Create file in Java
In this post, you will learn how to create and write file using the Java programming language.
File handling is an important part of the development process. Like other programming languages, Java also provides methods for file handling. Java provides several ways to write to a file. Here, we have mentioned most of them-
Java Create a File
To create a file in Java, we can use the createNewFile() method. This method returns a boolean value. It returns true, if the file was successfully created, and false otherwise. This method can throw an IOException if an error occurs. So, we enclosed the code in a try...catch block.
In the given Java program, we import the file class and IOException class.
import java.io.File;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
File myObj = new File("demo.txt");
if (myObj.createNewFile()) {
System.out.println("File created successfully.: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output of the above code:
File created successfully.: demo.txt
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number