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 class
MyClass
{ public static void main(String[] args) { File
file
= new File("
example.txt
");
//this will create a text file named example
try { 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 class
MyClass
{ public static void main(String[] args) { File
file
= new File("
example.txt
"); try { FileWriter
fw
= 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 class
MyClass
{ public static void main(String[] args) { File
file
= new File("
C:\\Users\\bharg\\Desktop\\example.txt
"); try { FileWriter
fw
= 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 class
MyClass
{ public static void main(String[] args) { File
file
= new File("
example.txt
"); try { FileWriter
fw
= new FileWriter(
file
);
//Used to wrap FileWriter
BufferedWriter
bw
= 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 class
MyClass
{ public static void main(String[] args) { File
file
= new File("
example.txt
"); try { FileOutputStream
fos
= new FileOutputStream(
file
);
// First take input as a string
String
line1
= "
Hello
";
// convert it into array of bytes
byte[]
arr1
=
line1
.getBytes();
// write to file
fos
.write(
arr1
); String
line2
= "
\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 class
MyClass
{ public static void main(String[] args) { System.out.println("
Welcome to FileWriter !
"); System.out.println("
--------------------------
"); System.out.println("
Enter a file name:
"); Scanner
scan
= new Scanner(System.in); String
fileName
=
scan
.nextLine(); File
file
= new File(
fileName
); FileWriter
fw
= 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:
"); int
entry
=
scan
.nextInt(); int
i
= 0; System.out.println("
--------------------------
"); System.out.println("
Enter contents in file:
"); while (
i
<=
entry
) { String
line
=
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: