Java Simple Program to write text data to a file

[info]You need to have JDK/Eclipse installed on your PC[/info]

1. Open Eclipse and REMEMBER the workspace location

2. New project : MyWriteFileProj   [ Click here for steps to create a new project ]

3. New Class under the project : MyWriteFile

4. Type in the following code under your class : MyWriteFile

import java.io.*;

public class MyWriteFile {

	public static void main(String[] args) {
		try{
			System.out.println("Starting my program !");
			FileWriter fs = new FileWriter("mydata.txt",true);
			BufferedWriter out = new BufferedWriter(fs);
			out.write("Imed,Bouchrika,SoukAhras,0444444\n");
			out.close();			
		}catch(Exception e){
			e.printStackTrace();
		}
	}		
}

5. Open Windows Explorer, Go to your Eclipse Workspace->MyWriteFileProj, open the file mydata.txt

FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content, However, when you specified a true value as the second argument in FileWritter constructor, it will keep the existing content and append the new content in the end of the file.

 

 

Leave a Reply

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