How to write text file in Java?

Below java code shows you efficient way to write the data to text file

/****************************************************************************************
 * Created on 08-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java.io;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by Vigilance India.
 * User: https://kodehelp.com
 * Date: Aug 1, 2011
 */
public class WriteTextFile {
    public static void main(String args[]){
        FileWriter fileWriter = null;
        try{
            String textToWrite = "This is the string which will be written in the text file";
            fileWriter = new FileWriter("/demo.txt");
            fileWriter.write(textToWrite);
        }catch(FileNotFoundException fnfEx){
            fnfEx.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fileWriter!=null)
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.