Java – How to Create file in Java

To create a file in java we need to use java.io package. File class is used to create a file at specific path. In java we can write file with FileWriter class with BufferedWriter class. write() method is used to create file and write the content in file.

Example will explain how to create a file in java and how to write file in Java

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;

public class JavaIOWriteFileExample {

    public static void main(String[] args) {

        File f=new File("c:\\createNewfile.txt");

        try{
            FileWriter fstreamCopy = new FileWriter(f);
            BufferedWriter outobjCopy = new BufferedWriter(fstreamCopy);
            outobjCopy.write("The content write to inside the file");
            outobjCopy.close();
         }
        catch (Exception e){
              e.printStackTrace();
         }
    }
}

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post