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


Page: < 1 2

(Continued from page 1)

Below is another example. In this example, a PrintWriter object is instantiated and is passed in its constructor a FileWriter object. Calls to the print method on the PrintWriter object get written to the File that the FileWriter object references. The println method of PrintWriter can be useful for including a linefeed automatically at the end of the String passed to the method. In the example below, the WriteStringToFile2 class writes "This is a test" to a file called "test2.txt".

WriteStringToFile2.java

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteStringToFile2 {
	
	public static void main(String[] args) {	
		try {
			File file = new File("test2.txt");
			FileWriter fileWriter = new FileWriter(file);
			PrintWriter printWriter = new PrintWriter(fileWriter);
			printWriter.print("This is ");
			printWriter.print("a test");
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
Page: < 1 2