How to write file in Java?

UPDATED: 29 June 2015
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {

    public static void main(String[] args) {
        /* Content to write in File. */
        String strFileData = "This excerpt demonstrate file writing in Java.";

        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        try {
            /* If file not exists at given location then create new File. */
            if (!objFile.exists()) {
                objFile.createNewFile();
            }

            /* Create object of FileWriter. */
            FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath());

            /* Create object of BufferedWriter. */
            BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);

            /* Write content to File. */
            objBufferedWriter.write(strFileData);

            /* Close the BufferedWriter */
            objBufferedWriter.close();
            
            System.out.println("File created!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Other References:
How to append text to an existing file in Java?
How to read file in Java?
How to read/parse XML file in Java?

0 comments :