File Writing Example

File Writing Example


Posted in : Java Posted on : March 29, 2012 at 7:16 PM Comments : [ 0 ]

In this tutorial you will learn how to write file using java

Java File Writing Example

To Write a file in Java, at first create a File reference variable and pass its references to FileWriter class as.

File file = new File("D:\\test-file.txt");
FileWriter fileWriter = new FileWriter(file, true);

Here true indicates that the file will append. If we make it false then

Make a PrintWriter reference variable by passing the FileWriter references to its constructor and call the print() method to write data to a file and finally close the objects.

PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println("Write Something to File");
fileWriter.close();

The Following is an example to write data to a file

JavaFileWritingExample.java

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

public class JavaFileWritingExample {
	public static void main(String[] args) {
		try {
			File file = new File("D:\\test-file.txt");
			FileWriter fileWriter = new FileWriter(file, true);
			PrintWriter printWriter = new PrintWriter(fileWriter);
			printWriter.println("Write Something to File");
			fileWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Download Select Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics