Java Tutorial-Java Files

Java Files


The java.io package contains the class File, allows working with the files.

To use the File class, create an object of the class, and specify the filename and directory name.


Example

import java.io.File;  //Import the File class
File myFile = new File("newfile.txt"); //Specify the filename

The File class contains many useful methods for creating and getting information about files as given below:


Method

Type

Description

canRead()

Boolean

Tests whether the file is readable or not

canWrite()

Boolean

Tests whether the file is writable or not

createNewFile()

Boolean

Creates an empty file

delete()

Boolean

Deletes a file

exists()

Boolean

Tests whether the file exists

getName()

String

Returns the name of the file

getAbsolutePath()

String

Returns the absolute pathname of the file

length()

Long

Returns the size of the file in bytes

list()

String[]

Return an array of the files in the directory

mkdir()

Boolean

Creates a directory