Home Tutorial Java Core Files Java write even numbers to file

 
 

Share on Google+Share on Google+
Java write even numbers to file
Posted on: September 4, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to write the even numbers to file.

Java write 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();
	}
}
Advertisement

Related Tags for Java write even numbers to file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 4, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com