In this article we are going to see how we can create and write into a file by using Java programming language.
Java Program to Create a File and Write into the File
As per problem statement first we have to create a file in a specified path then we have to write into the created file.
Let’s see program to understand it clearly.
- Java Program to Create a File and Write into the File by Using Java IO Library
- Java Program to Create a File and Write into the File by Using FileOutputStream
- Java Program to Create a File and Write into the File by Using NIO
Method-1: Java Program to Create a File and Write into the File by Using Java IO Library
In this method we will be using the IO library. We will be creating two objects, one File object to create a new file and another FileWriter object to write into the file.
Approach
- Create a
File
object with the file name as parameter. - Use the method
createNewFile( )
of theFile
class to create a new file inside an If block which will print upon successful creation of the file. - Now create a FileWriter object with the same filename as parameter.
- Write into the file using
write( )
method of theFileWriter
class. - Now close the file.
- Use a catch block to catch any IO exceptions and print it.
Program:
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { //try blockcreateNewFile() try { //Create object of File class and pass file name as parameter File fileObj = new File("BtechGeeks.txt"); //create the file by using inbuilt createNewFile() of File class if(fileObj.createNewFile()) { System.out.println("File "+fileObj.getName() +" has been created"); } //Create a writer object to write to the file & pass file name as parameter FileWriter writerObj = new FileWriter("BtechGeeks.txt"); //Writing to the file writerObj.write("BtechGeeks is one of the best platform to learn Java"); writerObj.close(); } //Catch block catch(IOException e) { System.out.println("Unable to complete the task"); // Print the exception occurred e.printStackTrace(); } //Prints on successful creation and writing in the file System.out.println("Successfully File Created and Written into File"); } }
Output:
Console Output:
File BtechGeeks.txt has been created Successfully File Created and Written into File
In File Explorer the file has been created:
Written text/content inside file:
Method-2: Java Program to Create a File and Write into the File by Using FileOutputStream
In this method we will be again using the IO library.
Method Used:
- getBytes( ): Convert the string characters into a byte array.
- write( ): Takes byte array as parameter and writes it into the file.
Approach:
- Create a
FileOutputStream
object with the file name. - Store the content to write in a string variable
- Convert the string into a byte array using
getBytes( )
method. - Now use the
write( )
method of the file class with the byte array as parameter to write into the file. - Now close the file.
Program:
import java.io.*; public class Main { public static void main(String[] args) { //try block try { // Created a FileOutputStream object with the file name as parameter FileOutputStream file = new FileOutputStream("file.txt", true); // The text to write into the file String text = "Hello World"; // Convert the string into bytes byte[] textByte = text.getBytes(); // Writing into the file file.write(textByte); file.close(); System.out.println("File written successfully"); } //Catch and print any IOException caused catch(IOException e) { System.out.println("Unable to create file. Exception - "+e); } } }
Output:
In Console:
File written successfully
In File Explorer:
Method-3: Java Program to Create a File and Write into the File by Using NIO
Java NIO package is also another package that handle IO operations and it might seem a replacement to JavaIO but it is not. Both IO and NIO packages are used here together.
Approach:
- Store the file path in a string variable
- Now create a
Path
object to store the path - Create the file using
Files.createFile()
method using the path and store its path in another path object - Print the path of the object to the console
- Now use a
FileWriter
object with the same path to create an object and write into the file - Close the file
- Catch any exceptions if caused and print the error
Program:
import java.io.*; import java.io.*; import java.nio.file.*; public class Main{ public static void main(String[] args) { //Declare a string variable as assign the file path as value String filePath = "C:\\Users\\DELL\\eclipse-workspace\\BtechGeeks_File.txt"; // Creating a Path object from the file path Path path = Paths.get(filePath); //try block try { //Creating a file by using createFile() method //and storing its path in a path object p Path p = Files.createFile(path); // Printing the file path to console System.out.println("File created at "+p); //Creating a FileWriter object and writing to the file FileWriter file = new FileWriter(filePath,true); file.write("Hello World"); file.close(); System.out.println("Successfully wrote to the file"); } //Catch and print any IOException caused catch(IOException e) { System.out.println("Unable to create file. Exception - "+e); } } }
Output:
In Console:
File created at C:\Users\DELL\eclipse-workspace\BtechGeeks_File.txt Successfully wrote to the file
In File Explorer:
Written text/content in file:
Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.