In this section, you will learn how to write the even numbers to file.
In this section, you will learn how to write the even numbers to file.In this section, you will learn how to write the even numbers to file.
By using the PrintWriter class, you can write any type of data to the file. It has wide variety of methods for different primitive data types. It has a wide selection of constructors that enable you to connect it to a File, an Output Stream, or a Writer.
In the given example, we have created an instance of PrintWriter and used FileWriter as an argument. Then we have started a loop for numbers 1 to 50. If the number is totally divided by 2 leaving 0 remainder, then it should be an even number and stored in the file. We have used print() method to store the even numbers to the file.
println(): This method of PrintWriter class terminates the current line by writing the line separator string.
Here is the code:
import java.io.*; public class WriteEvenNumbersToFile { public static void main(String[] args) throws Exception { PrintWriter pw = new PrintWriter(new FileWriter("C:/evens.txt")); for (int i = 1; i <= 50; i++) { if (i % 2 == 0) { pw.print(i); pw.println(); } } pw.close(); } }