Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How to Write a File in Java

In this post, we are going to learn how to write data to a file. Data can be a single character, a sequence of characters, or a multi-line string.

To write data to a file, we are using Files class of Java. The Files class provides several methods to write data to a file such as write bytes, string or iterable etc.

Here, we will use write() method to write a string and list of string as well. For writing purposes, we are using a file outfile.txt that stores the written data.

We recommend you create a file prior to write, However, Java creates the file automatically if the file is not present.

Time for an Example:

Now, let's see an example to write data to a file. Here, we have a file outfile.txt that will be used to store the data and write() method of the Files class is used for that purpose. The method writes data in bytes format, so we converted the string to bytes using the getBytes() method.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; 
public class Main {
	
	public static void main(String[] args) throws IOException{  
		String lines = "Welcome to Studytonight.com \n It is technical portal.";
		Path path = Paths.get("outfile.txt");
		Files.write(path, lines.getBytes());
	}
}

After executing the above code, you can open and see the file outfile.txt in the same directory.

Time for another Example:

Let's take another example to write data to a file. Here, we are writing a list of string to the file and in the write() method we specified the standard charset as well. This method is one of the override versions of write() method.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.nio.charset.*;
 
public class Main {
	
	public static void main(String[] args) throws IOException{  
		List<String> lines = Arrays.asList("Welcome to Studytonight.com", "It is technical portal.");
		Path path = Paths.get("outfile.txt");
		Files.write(path, lines, StandardCharsets.UTF_8);
	}
}

After the successful execution of the above code, you can see the outfile.txt file that must contain the written data as given below.

// File: outfile.txt


Welcome to Studytonight.com
It is technical portal.