Java write file

This Java tip shows you how to write data to a text file. In Java, you can use FileWriter to characters or string to a text file. If you want to write text line by line to the file, you will need to wrap the FileWriter object in the BufferedWriter object.

-import java io package
-create FileWriter object that specifies file name
-create BufferedWriter object
-use write() method of BufferedWriter to write text to the file


import java.io.*;
public class WritingFile{
  public static void main(String[] args){
 
      try{ //catch errors if any
         FileWriter fw=new FileWriter("test.txt");
         BufferedWriter bw=new BufferedWriter(fw);
         bw.write("I am outside now.");//write text to the file using write method

         bw.newLine(); //output a new line

         bw.write("Now, i am at home.");
         bw.flush();//write any buffered text to the file
         bw.close();//close file using close() method

  
  } catch(IOException ie){System.out.println("Error in writing to file...");}

  
  }
}

To write text containing Unicode characters to a file, you can use DataOutputStream class.

import java.io.*;
public class WritingEncode{
  public static void main(String[] args){
       writeunicode();
     }
   public static void writeunicode(){

   try{ //catch errors if any

   DataOutputStream out=new DataOutputStream(new FileOutputStream("test.txt"));
   out.writeUTF("កម្ពុជា�);//write text to the file using writeUTF method
   out.close();//close file using close() method  
   } catch(IOException ie){System.out.println("Error in writing to file...");}
  }
  

}

Posted by: Dara | post date: 01-25-2013 | Subject: Java Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.