How to make a file in java


 

How to make a file in java

This tutorial demonstrate how to make a file and write text in java. Here a text file is made using the File Class.

This tutorial demonstrate how to make a file and write text in java. Here a text file is made using the File Class.

Description:

This example demonstrate how to make a file and write string in it. To create a file in java we use the File Class. The instance of the File class is immutable that means the pathname represented by the File object will never change.

 Code:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FilePermission;
import java.util.PropertyPermission;

public class WriteToFile {

  public static void main(String[] args) {
    try {
      File makefile = new File("output.txt");
      FileWriter fwrite = new FileWriter(makefile);
      fwrite.write("This is ");
      fwrite.write("a example");
      fwrite.write("of FileWriter");
      fwrite.flush();
      fwrite.close();
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Output:

It will create a file name ouput.txt at the current directory. The output.txt file have "This is a example of FileWriter" content written inside. 

Ads