File Class in java

File f = new File("abc.txt");
  • The above line won’t create a physical file but it will check if file is available with that name.
  • If the file is available the object f will point to that file.
  • If the files doesn’t exist then it just creates a java File object to represent a file name ‘abc.txt’ but it won’t actually create any physical line

How to create a new file in java?

File f = new File("abc.txt");
f.createNewFile();

How to create a new directory in java?

File f = new File("/home/tyson/HelloWorld");
f.mkdir();

How to check if a file or a directory exist in java?

File f1 = new File("abc.txt");
File f2 = new File("/home/tyson");
f1.exist()
f2.exist()

Note : Java IO Concept is implemented based on the UNIX OS concept and in unix everything is treated as a File.Hence we can use java file object to represent both file and directories.

File Class Constructors :

File f1 = new File(String name);
//Creates f1 object representing file or directory
File f2 = new File(String subDir, String name);
//Creates f2 object within a subdirectory
File f3 = new File(File subDir, String name);

File Class important methods :

boolean exist();
boolean createNewFile();
boolean mkdir();
boolean isFile();
boolean isDirectory();
String[] list(); //returns names of all files and directory present in a directory
long length(); //returns number of characters present in the specified file.
boolean delete(); //deletes a file or directory.

Program to print the list of files and directories in a directory in java :

package com.fileDemo;

import java.io.File;

public class ListOfFilesDemo {
	public static void main(String[] args) {
		File f = new File("/home/tyson/Desktop/temp");
		String[] listOfFiles = f.list();
		for(String name : listOfFiles) {
			System.out.println(name);
		}
	}
}

Leave a Comment