Java                                                          Home : www.sharetechnote.com

 

 

 

 

Java - FileWriter

 

 

 

FileWriter01.java

import java.io.*;

 

public class FileWriter01 {

 

    public static void main(String[] args) {

        

      File file = null;

      FileWriter writer = null;     

      

      try {

        file = new File("temp.txt");

        

        if(file.createNewFile()) {

            System.out.println("File Created Successfully");

        } else {

            System.out.println("File already exists.");

        };

        

        writer = new FileWriter(file);

      } catch(Exception e) {

        System.out.println(e);  

      };

      

      

      try {

        writer.write("Hello World\r\n");

        writer.write("Hello\r\n");

        writer.write("World\r\n");      

        writer.close();

      } catch(Exception e) {

        e.printStackTrace();

      };

      

    }

 

}

 

      Output : The conents of temp.txt

       

        Hello World

        Hello

        World

 

 

 

FileWriter02.java

import java.io.*;

 

public class FileWriter02 {

 

    public static void main(String[] args) throws IOException {

        

        File file = null;

        FileWriter writer = null;   

          

        file = new File("temp.txt");

        

        if(file.createNewFile()) {

            System.out.println("File Created Successfully");

        } else {

            System.out.println("File already exists.");

        };

        

        writer = new FileWriter(file);

      

        writer.write("Hello World\r\n");

        writer.write("Hello\r\n");

        writer.write("World\r\n");      

        writer.close();

      

    }

 

}

 

      Output : The conents of temp.txt

       

        Hello World

        Hello

        World