Monday, September 7, 2009

Java Code to Write to a File

Welcome back to Java Code Online. The article for today is for writing some text to a file in Java. There are often various cases when we need to write or save some data in an external file. Java provides a very powerful set of libraries for handling this operation.

First for writing to a file you need to have write permission on it, So first we need to check that whether we can write on it or not. If the file is writable, then we use the FileWriter class provided by Java to perform this operation. This file is part of the java.io package, which includes many powerful classes for handling the Java input output operations.

The writing to a file operation is used in many cases like when we need to save some content in a file, which could be read or used afterward. this file may also be sent to some other application for some other operations required on it.

The Java Code for writing to a file is provided below. We assumed a path as per our local machine. You need to set the path according to your folder structure. This code writes the content in a file. If the file is not present, then it creates one and then write to it. So anyhow your writing operation will be successful.

The Java Code is:-

////////////////////////

package developer;

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

public class WriteToFile {


public static void main(String[] args) throws IOException {
//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.txt");
PrintWriter pw = new PrintWriter(fw);

//Write to file line by line
pw.println("Hello guys");
pw.println("Java Code Online is testing");
pw.println("writing to a file operation");

//Flush the output to the file
pw.flush();

//Close the Print Writer
pw.close();

//Close the File Writer
fw.close();
}
}


////////////////////////

The beauty of the code lies in its compactness and simplicity of use. Note the use of flush on the PrintWriter Class Object. This helps in writing any buffered output to the file. This ensures that all the content is written to the file, before the writer is closed.

I hope the code for writing to a file was useful to all. Keep posting comments, because that's the way we can be in touch. Keep checking Java Code Online for more Java articles.

Related Java articles:-
Java Code to Read a File

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.