Write Text File in Java


How to Write Text File in Java?

Java Write File

Java Write Text File

Write File

Write File in Java

Write Text File

Following is the complete program to write the text in file using PrintWriter Class.

package raghuwansh.java;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class WriteTextFile {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PrintWriter printWriter = null;
		try {
			// Will overwrite the file if exists or creates new
			printWriter = new PrintWriter(
					"C:/workspaceeclipse/raghuwansh/src/raghuwansh/java/textfile.txt",
					"UTF-8");
			printWriter.println("line 1");
			printWriter.println("line 2");
		} catch (FileNotFoundException fileNotFoundException) {
			fileNotFoundException.printStackTrace();
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
			unsupportedEncodingException.printStackTrace();
		} finally {
			printWriter.close();
		}

	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *


8 − = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>