How to Write to a File in Java
To store data temporarily or permanently for programming purposes, we need to write data to a file. There are many classes and methods in Java to write data in a file. How different classes and methods can be used in Java to write data in a file are shown in this tutorial.
Some necessary classes and method for writing file:
writeString() method:
This method is supported by Java version 11. It can take four parameters. These are file path, character sequence, charset, and options. The first two parameters are mandatory for this method to write into a file. It writes the characters as the content of the file. It returns the file path and can throw four types of exceptions. It is better to use when the content of the file is short.
FileWriter Class:
If the content of the file is short, then using the FileWriter class to write in the file is another better option. It also writes the stream of characters as the content of the file like writeString() method. The constructor of this class defines the default character encoding and the default buffer size in bytes.
BufferedWriter Class:
It is used to write text to a character-output stream. It has a default buffer size, but the large buffer size can be assigned. It is useful for writing character, string, and array. It is better to wrap this class with any writer class for writing data to a file if no prompt output is required.
FileOutputStream Class:
It is used to write raw stream data to a file. FileWriter and BufferedWriter classes are used to write only the text to a file, but the binary data can be written by using the FileOutputStream class.
The following examples show the uses of the mentioned method and classes.
Example-1: Write to a file using writeString() method
The following example shows the use of the writeString() method that is under Files class to write data into a file. Another class, Path, is used to assign the filename with a path where the content will be written. Files class has another method named readString() to read the content of any existing file that is used in the code to check the content is properly written in the file.
import java.nio.file.Files ;
import java.nio.file.Path ;
import java.io.IOException ;
public class fwrite1 {
public static void main( String [ ] args) throws IOException
{
//Assign the content of the file
String text= "Welcome to Linuxhint\nLearn java from the basic" ;
//Define the file name of the file
Path fileName = Path.of ( "file1.txt" ) ;
//Write into the file
Files.writeString (fileName, text) ;
//Read the content of the file
String file_content = Files.readString (fileName) ;
//Print the file content
System.out.println (file_content) ;
}
}
Output:
The following output will appear after running the code. Here, two lines are written in the file that is shown in the output.
Example-2: Write to a file using FileWriter class
The following example shows the use of the FileWriter class to write content into a file. It requires to create the object of the FileWriter class with the filename to write into a file. Next, the write() method is used to write the value of the text variable in the file. If any error occurs at the time of writing the file, then an IOexception will be thrown, and the error message will be printed from the catch block.
//Import necessary packages
import java.io.FileWriter ;
import java.io.IOException ;
public class fwrite2 {
public static void main( String [ ] args) {
//Assign the file content
String text = "The latest Java version contains important enhancements
to improve performance, " + "stability and security of the Java
applications that run on your machine. " ;
try
{
//Create a FileWriter object to write in the file
FileWriter fWriter= new FileWriter ( "file2.txt" ) ;
//Write into the file
fWriter.write (text) ;
//Print the success message
System.out.print ( "File is created successfully with the content." ) ;
//Close the file writer object
fWriter.close ( ) ;
}
catch ( IOException e)
{
//Print the error message
System.out.print (e.getMessage ( ) ) ;
}
}
}
Output:
If the file content is written successfully in the file, then the following output will appear. You can check the project folder to confirm that the file is created properly or not.
Example-3: Write to a file using BufferedWriter class
The following example shows the use of BufferedWriter class to write into a file. It also requires to create the object of BufferedWriter class like FileWriter to write content into the file. But this class supports large content to write into the file by using a large buffer size.
import java.io.BufferedWriter ;
import java.io.FileWriter ;
import java.io.IOException ;
public class fwrite3 {
public static void main( String [ ] args) {
//Assign the file content
String text = "Learn Java easily from LinuxHint" ;
try {
//Create an object of BufferedWriter
BufferedWriter f_writer = new BufferedWriter ( new FileWriter ( "file3.txt" ) ) ;
f_writer.write (text) ;
//Print the success message
System.out.print ( "File is created successfully with the content." ) ;
//Close the BufferedWriter object
f_writer.close ( ) ;
}
catch ( IOException e)
{
//Print the error message
System.out.print (e.getMessage ( ) ) ;
}
}
}
Output:
If the file content is written successfully in the file, then the following output will appear. You can check the project folder to confirm that the file is created properly or not.
Example-4: Write to a file using FileOutputStream class
To write data into a file using FileOutputStream class is shown in the following example. It also requires to create the object of the class with the filename to write data into a file. Here, the string content is converted into the byte array that is written into the file by using the write() method.
import java.io.FileOutputStream ;
import java.io.IOException ;
public class fwrite4 {
public static void main( String [ ] args) {
//Assign the file content
String fileContent = "Welcome to LinuxHint" ;
try {
//Create an object of FileOutputStream
FileOutputStream outputStream = new FileOutputStream ( "file4.txt" ) ;
//store byte content from string
byte [ ] strToBytes = fileContent.getBytes ( ) ;
//Write into the file
outputStream.write (strToBytes) ;
//Print the success message
System.out.print ( "File is created successfully with the content." ) ;
//Close the object
outputStream.close ( ) ;
}
catch ( IOException e)
{
//Print the error message
System.out.print (e.getMessage ( ) ) ;
}
}
}
Output:
If the file content is written successfully in the file, then the following output will appear. You can check the project folder to confirm that the file is created properly or not.
Conclusion:
Multiple ways to write into a file are shown in this tutorial by using different Java classes. The user can select any of the classes mentioned here to write into a file based on the content of the file.
About the author
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
How to Write to a File in Java
Source: https://linuxhint.com/writing_files_java/