Write Text Files Using Java

On February 28, 2011, in Java, Programming, Software Development, by LuCuS

Pen and PaperHere is another example from my book, “Quick Coding and Automation with Java”. In this example, I show you how to write to a text file using Java IO. For this example, you will only need 2 objects instantiated. The first object is the FileWriter. We will pass this object the name of the file we wish to write. In the code sample below, I chose to use “C:\TestFile.txt”, but you can change this to any file you want. Just be sure to escape the backslashes as shown below. The second object you will need to instantiate is the BufferedWriter. You will pass the FileWriter we created above to the BufferedWriter constructor. That’s all there is to it. The only thing you have left to do is to call the “write” method on the BufferedWriter, passing in any text you want written to your file. When you’re finished writing to the file, be sure to call the “close” method on the BufferedWriter, otherwise your file will stay open and will not be usable until you close it. Here is the code that I used in my book. You’ll notice that it’s fairly small when you don’t include the comments like I did.

import java.io.FileWriter;
import java.io.BufferedWriter;

public class TextWriter { 
  public static void main(String[] args) throws Exception {
	// Define our output file
    FileWriter outputFile = new FileWriter("C:\TestFile.txt"); 
    // Initialize our buffered writer
    BufferedWriter out = new BufferedWriter(outputFile);
    // Example output
    out.write("This is a test of the emergency broadcast system.rn");
    // Loop 5 times and print the value of i each time through
    for(int i = 1; i <= 5; i++)
    	out.write("i = " + i + "rn");
    // Close the buffered writer

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.

Related Posts

Tagged with:  

Leave a Reply