Thursday, April 16, 2009

Java IO: Simple Java Program To Write Text File

Here is the simple java code to write text file.You need to import java.io package...
Used File, FileWriter & BufferedWriter. Simply copy paste the below code and run the code.




/* here is the complete code for WriteFile.java */


import java.io.*;

public class WriteFile
{
public static void main(String[] args)
{
//name of the file, it takes default path ie. current directory
String TextFileToWrite = "MyFile.txt";

try
{
File file=new File(TextFileToWrite);
FileWriter fw =new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

for(int line = 0 ; line <= 10 ; line ++)
{
bw.write("this is line " + line );
bw.newLine();
bw.flush();//flushing
}

bw.close();//closeing BufferedWriter

System.out.println("File Written sucessfully!!!");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

No comments:

Post a Comment