How do I write a String to a File?
Author: Deron Eriksson
Description: This Java tutorial describes how to write a String to a File.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1
In JavaSW, there are a multitude of ways to write a String to a File. Perhaps the cleanest, most succinct solution to write a String to a File is through the use of the FileWriter. With this class, you pass its constructor the File object that you'd like to write to, and then you call its write method to write strings of data to the file. When done, you can flush and close the FileWriter, and you're done. In the example below, the WriteStringToFile1 class writes "This is a test" to a file called "test1.txt". WriteStringToFile1.javapackage test; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteStringToFile1 { public static void main(String[] args) { try { File file = new File("test1.txt"); FileWriter fileWriter = new FileWriter(file); fileWriter.write("This is "); fileWriter.write("a test"); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } (Continued on page 2) Related Tutorials:
|