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. WriteStringToFile.javapackage test; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; 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: test.txtThis 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) Related Tutorials:
|