|
FAQ: How do I write text to a file using Java?
Answer: I've found the most convenient way to do this is with a FileWriter and a PrintWriter. I use both a FileWriter and a PrintWriter because although the PrintWriter has more convenience methods to write with, the FileWriter will throw an exception on instantiation if something goes wrong (such as trying to write to a directory instead of a file), while the PrintWriter does not.
Here's a complete sample Java program that demonstrates this file-writing process. I create a File, wrap that in a FileWriter, then wrap that in a PrintWriter.
package com.devdaily.javasamples;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Demonstrates how to write to a file using Java.
* Uses a File, FileWriter, and PrintWriter.
* The PrintWriter offers many convenience methods for writing text.
* Created by Alvin Alexander, http://devdaily.com.
*/
public class JavaWriteTextToAFileExample
{
public static void main(String[] args)
{
PrintWriter pw = null;
try
{
pw = new PrintWriter(new FileWriter(new File("/Users/al/HelloWorld.txt")));
// a print writer gives you many more methods to write with
pw.println("Hello, World");
}
catch (IOException e)
{
e.printStackTrace();
// deal with the exception
}
finally
{
pw.close();
}
}
}
|