Creating & Writing Text Files in Java (Part 6)
Pre-requisites:- Exception Handling , Reading Files
Creating a Text File
A text file can be created by many ways , here I will try to show the most used ways to create a text file. Firstly , we will learn to create a text file by using File class which is by far the most popular way to create a text file.
- First we have to create an instance of File class , then we have to call a method .createNewFile( ) which is a boolean i.e will return true or false.
- Also this method is suspicious of throwing an IOException so we have to catch it using a try-catch block.
- If file is created the .createNewFile( ) returns true if file is created or if file name mentioned exists previously in any form returns a false value.
import java.io.File; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("example.txt");//this will create a text file named exampletry { if(file.createNewFile()==true) { System.out.println("New File created:"+file.toString()); } else { System.out.println("The file already exists:"+file.toString()); } } catch (IOException e) { System.out.println("Unable to perform I/O operations on file:"+file.toString()); } finally { System.out.println("File is located at:"+file.getAbsolutePath()); } } }
Output:-
New File created: example.txt
File is located at: C:\Users\workspace\JavaProgram1\example.txt
Here the method .getAbsolutePath( ) returns the path of the file where it is saved in the system.
Writing a Text File
There are two ways to write a text file in Java :
1. Without specifying location of the file
- For this , we must create a text file in our own folder where our code is written.
- First In the Left-side section i.e where your projects are displayed , right-click on your project then a pop-up menu will open select New and then File.
- Give your file a name with extension .txt mentioning it is text file and that name would be used in the code.
Now when you have declared a file , its time to apply your logic into the java code. Here we are using the FileWriter class to write data into files.
import java.io.File; import java.io.FileWriter; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("example.txt"); try { FileWriterfw= new FileWriter(file);fw.write("Hello");fw.write("\n");fw.write("Welcome");fw.write("\n");fw.write("To Java Monk");fw.close(); } catch (IOException e) { System.out.println("Unable to read/write file"); } } }
Output:- ( In File )
Hello
Welcome
To Java Monk
2. By specifying location of the file
We also can create a text file where we have to give an instance path to the file we have created. The file will be stored at that location in our system.
import java.io.File; import java.io.FileWriter; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("C:\\Users\\bharg\\Desktop\\example.txt"); try { FileWriterfw= new FileWriter(file);fw.write("Hello");fw.write("\n");fw.write("Welcome");fw.write("\n");fw.write("To Java Monk");fw.close(); } catch (IOException e) { System.out.println("Unable to read/write file"); } } }
Output:-
We also can use many other ways to write a file:
1. Using BufferedWriter
BufferedWriter is used when number of file operations are more because it performs better than the FileWriter.
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("example.txt"); try { FileWriterfw= new FileWriter(file);//Used to wrap FileWriterBufferedWriterbw= new BufferedWriter(fw);bw.write("Hello");bw.write("\n");bw.write("Welcome");bw.write("\n");bw.write("To Java Monk !");bw.write("\n");bw.write("------Written by BufferedWriter");bw.close(); } catch (IOException e) { System.out.println("Unable to read/write file"); } } }
Output:- ( In File )
Hello
Welcome
To Java Monk !
------Written by BufferedWriter
2. Using FileOutputStream
When any raw stream data is to be written , FileOutputStream is used.
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("example.txt"); try { FileOutputStreamfos= new FileOutputStream(file);// First take input as a stringStringline1= "Hello";// convert it into array of bytesbyte[]arr1=line1.getBytes();// write to filefos.write(arr1); Stringline2= "\n"; byte[]arr2=line2.getBytes();fos.write(arr2); String line3 = "----Written by FileOutputStream"; byte[]arr3=line3.getBytes();fos.write(arr3);fos.close(); } catch (IOException e) { System.out.println("Unable to read/write file"); } } }
Output:- ( In File )
Hello
----Written by FileOutputStream
Also there are more functionalities through which we can read files , but for now you must know the above functionalities used to write files.
Let's see a program where user can input the contents of file in it . Here I have used FileWriter to write contents to file.
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public classMyClass{ public static void main(String[] args) { System.out.println("Welcome to FileWriter !"); System.out.println("--------------------------"); System.out.println("Enter a file name:"); Scannerscan= new Scanner(System.in); StringfileName=scan.nextLine(); Filefile= new File(fileName); FileWriterfw= null; try {fw= new FileWriter(file); System.out.println("--------------------------"); System.out.println("File created:" +file.toString()); System.out.println("File Location:" +file.getAbsolutePath()); System.out.println("--------------------------"); System.out.println("Enter number of lines you wish to write on file:"); intentry=scan.nextInt(); inti= 0; System.out.println("--------------------------"); System.out.println("Enter contents in file:"); while (i<=entry) { Stringline=scan.nextLine();fw.write(line+"\n");i++; } System.out.println("--------------------------"); System.out.println("File Saved:" +file.toString()); System.out.println("--------------------------"); System.out.println("You can check out your file at location:"+file.getAbsolutePath()); } catch (IOException e) { System.out.println("Unable to read/write on file:" +file.toString()); } finally { try {fw.close(); } catch (IOException e) { System.out.println("Unable to close file:" +file.toString()); } } } }
Output:-
Welcome to FileWriter !
--------------------------
Enter a file name:
example.txt
--------------------------
File created: example.txt
File Location: C:\Users\bharg\workspace\Example\example.txt
--------------------------
Enter number of lines you wish to write on file:
5
--------------------------
Enter contents in file:
Hello
I am Java Monk
Trying to make world a better place by teaching Java to all the beginners
Wrote that because I was not able to think of something else
Thank You
--------------------------
File Saved: example.txt
--------------------------
You can check out your file at location: C:\Users\bharg\workspace\Example\example.txt
In File:




