Core Java Tutorial

Core Java Tutorial

How to Create and Manupulate file in Java

File

An abstract representation of file and directory pathnames, File class help developer to work with files like creating, renaming, deleting etc…

Example

 

import java.io.File;

import java.io.IOException;


public class FileExample {


 public static void main(String[] args) {


  File f1 = new File("sam.txt");

  boolean b = false;

  try {

   b = f1.createNewFile();

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }


  System.out.println(b);


  System.out.println("last modified :" + f1.lastModified());

  System.out.println("length of the file :" + f1.length());


 }

}

File will not be created if the directory already has the file that we are trying to create. createNewFile() will return false if the file already exist.

Execute the above program and check the current directory to find the created file.