Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Write File in Java Easily

Tags: class write java

In this tutorial, we will learn how to Write a file in Java. We need to read and write files in many applications.

Java programming language supports both reading and writing text and binary files. But we will cover only to write text file here.

There are several ways to write a text file. Java provides several classes and methods to write a file. They are as:

  • Using FileWriter Class
  • Using writeString() method
  • By using BufferedWriter Class
  • By using FileOutputStream Class

Let’s understand all ways one by one with the help of example programs.

Writing File in Java using FileWriter class


The most basic way to write a file in Java is by using FileWriter class of java.io package.

FileWriter in Java is an output stream that writes data as characters into the text file using the platform’s default character encoding and buffer size. It is useful when we want to:

  • write text into a specific file.
  • append text in a file.
  • copy text from one file to another file.

FileWriter class is a subclass of OutputStreamWriter class that extends the Writer class.


There are the following steps to use FileWriter class to write a text file in Java. They are:

  1. Create an object of FileWriter class associated with the text file we want to write.
  2. Use write() method to write into a file inherited from Writer class.
  3. Close the file.
  4. Display a message “File successfully written…”.

Let’s create a Java program to write a text file using write() method inherited from Writer class.

Program code 1:

package javaProgram;
import java.io.FileWriter;
import java.io.IOException;
public class WritingFile {
public static void main(String[] args) throws IOException 
{
// Create a FileWriter object to open the file.
   FileWriter fw = new FileWriter("D:\\myfile.txt");

// To write text to the file, call write() method inherited from Writer class.
   fw.write("Welcome to Scientech Easy \n"); // Writing text to the file.
   fw.write("I love Java Programming");
   
   fw.close(); // Closing the file.
   System.out.println("Successfully written...");
   }
}
Output:
     Successfully written...

Data written to the file:

Welcome to Scientech Easy
I love Java Programming

In this example program, we have created a FileWriter object, specifying the name of a file as either String or File reference. The write() method inherited from Writer class has been used to write lines of text.

If you are writing multiple lines of text, must use newline. Without the newline, the next string would start on the same line, immediately after the previous one.


Let’s create a Java program to write a text file in Java using FileWriter and Scanner classes. We will prompt to write text into a file from the user. Look at the source code given below.

Program code 2:

package javaProgram;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WritingFile {
public static void main(String[] args) throws IOException 
{
// Create a FileWriter object to open the file.
   FileWriter fw = new FileWriter("D:\\myfile.txt");

// Create a Scanner class object to take input from the keyboard.
   Scanner sc = new Scanner(System.in);
   System.out.println("Write your content: ");
   String str = sc.nextLine();
   
// To write text to the file, call write() method inherited from Writer class.
   fw.write(str); // Writing text to the file.
   
   fw.close(); // Closing the file.
   System.out.println("Successfully written...");
   }
}
Output:
      Write your content: 
      Welcome to Scientech Easy to learn various technologies. 
      You can learn everything in an easy way on this site.  
      Successfully written...

Data written into a file:

Welcome to Scientech Easy to learn various technologies. You can learn everything in an easy way on this site.

Write Text File in Java using writeString() method


Java 11 has introduced writeString() method in the Files class. The writeString() method writes a sequence of characters such as String and StringBuilder to a text file.

The general syntax of this method is as follows:

Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)

This method returns nothing. It can take four parameters. These are:

  • path – It is a file path of data type Path.
  • csq – It is a sequence of characters as string which we will enter into a file.
  • cs – It is a UTF-8 Charset used to write the content to file.
  • options – This parameter provides different options to enter the string in the file, such as append the string to a file, overwrite anything in the file with the current string, etc.

Writing a text file using this method, the first two parameters are mandatory. The writeString() method can throw four types of exceptions.

They are IllegalArgumentException, IOException, UnsupportedOperationException, and SecurityException. Therefore, it is better to use when the file content is short.


Let’s make a Java program to write contents in the text file in Java using writeString() method of Files class. Look at the following code.

Program code 3:

package javaProgram;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WritingFile {
public static void main(String[] args) throws IOException 
{
// Create a string literal to assign the content of the file.
   String text = "Welcome to Scientech Easy\nHappy Learning!";

// Defining the name of the file with location.
   Path fileName = Path.of("D:\\myfile.text");

// Call writeString() method for writing the content into the file.
   Files.writeString(fileName, text);

// Call readString() method for reading the content of the file.
   String fileContent = Files.readString(fileName);

// Displaying the content inside the file.
   System.out.println(fileContent);
   }
}
Output:
      Welcome to Scientech Easy
      Happy Learning!

In this example program, we have used writeString() method of Files class to write content into a file. We have used path class to assign filename with path where the content of file has written.

Files class in Java also provides another method named readString() to read the content of any existing file. We have used it to check the content is properly written into the file or not.

Write a Text File in Java using BufferedWriter class


BufferedWriter class in Java write text to a character-output stream. It buffers the stream of characters before writing them to an underlying output stream. It has a default buffer size, but we can also assign a large buffer.

BufferedWriter class is useful for writing characters, strings, and arrays. Writing a text file using BufferedWriter class is optional.

We can also write a text file without using a buffer. But using a buffer for writing makes the writing process more efficient.

So, let’s create a Java program to write a text file using BufferedWriter class. There are the following steps to write a text file using FileWriter and BufferedWriter classes. They are:

  1. Create an instance of FileWriter class associated with a text file we want to write.
  2. Create an object of BufferedWriter class associated with FileWriter object.
  3. Write to the buffer.
  4. Flush the buffer.
  5. Close the buffer.

Program code 4:

package javaProgram;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WritingFile {
public static void main(String[] args) throws IOException 
{
// Create an object of FileWriter class.	
   FileWriter fw = new FileWriter("D:\\myfile.txt");

// Create an object of BufferedWriter class and reference variable fw to its constructor.
   BufferedWriter bw = new BufferedWriter(fw);
  
   bw.write("This is an apple");
   bw.newLine(); // For line separator.
   bw.write("This is an orange");
   bw.flush(); // flushing the buffer.
   bw.close(); // Closing the stream.
   System.out.println("File written successfully.");
  }
}
Output:
      File written successfully.

Content written into the file is:

This is an apple
This is an orange.

The preceding example program demonstrates the use of BufferedWriter class to write into a file. The bufferedWriter class first packages up many small requests in its own internal buffer.

Then when the buffer is full, or flush() method is invoked, BufferedWrite class writes the whole buffer into a text file in one go. We have used flush() method to flush the buffer and close() method to close the file.

Writing Text File Using FileOutputStream Class


FileOutputStream class in Java provides methods for writing data to a text file or to a FileDescriptor. It stores the content or data as individual bytes.

But, we can write both byte-oriented and character-oriented data via FileOutputStream class. For character-oriented data, you should use FileWriter class or BufferedWriter class rather than FileOutputStream.

The following example program shows the use of FileOutputStream class to write data into a file.

Program code 5:

package javaProgram;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class WritingFile {
public static void main(String[] args) throws IOException 
{
 try 
 { 
// Store the filepath into a variable filepath of type String.
   String filepath = "D:\\fileout.txt";

// Create FileOutputStream object to attach file with FileOutputStream and pass filepath to its constructor.	 
   FileOutputStream fos = new FileOutputStream(filepath);
   
   String str = "Welcome to Scientech Easy, Dhanbad"; 
   byte bytearray[ ] = str.getBytes(); // Converting string into byte array.   
   fos.write(bytearray);    
   fos.close(); // Closing file.    
   System.out.println("Successfully written...");    
 } 
 catch(FileNotFoundException e){
   System.out.println(e);
 }    
  }
}
Output:
      Successfully written...

Date written into the file is:

Welcome to Scientech Easy, Dhanbad

In this example, we have used byte array to convert string content into byte array. The write() method will write it into the specified text file. Thus, we can use FileOutputStream to write data into a text file easily.


In this tutorial, you have learned different ways to write a text file using various classes and methods with examples. Hope that you will have understood the basic concepts for writing the content into a text file and practiced all programs based on it.
Thanks for reading!!!

The post How to Write File in Java Easily appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

How to Write File in Java Easily

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×