How do I write a String to a File using Commons IO?
Author: Deron Eriksson
Description: This Java tutorial describes an easy way to write a String to a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The ApacheSW Commons IOS library has some great tools for working with files. As an example, the writeStringToFile method of the FileUtils class offers a very easy way to write a String to a File. This is demonstrated below.

package test;



public class WriteStringToFile {

	public static void main(String[] args) throws IOException {
		String string = "This is\na test";
		File file = new File("test.txt");
		FileUtils.writeStringToFile(file, string);

This generates the test.txt file with the expected output, shown below:


This is
a test

It should be noted that if you need use a different encoding, you can do so via

FileUtils.writeStringToFile(File file, String data, String encoding)