Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Files

Java Files

File handling constitutes a crucial aspect of any application.

Java provides various methods for creating, reading, updating, and deleting files.

Java File Handling

The File class from the java.io package facilitates file manipulation.

To utilize the File class, instantiate an object of the class and specify the filename or directory name.

Example

import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename
If you’re unfamiliar with the concept of a package, refer to our Java Packages Tutorial for clarification.

The File class offers numerous helpful methods for file creation and retrieval of file information. For instance:

Method

Type

Description

canRead()

Boolean

Determines whether the file is readable

canWrite()

Boolean

Checks whether the file is writable or not.

createNewFile()

Boolean

Generate an empty file.

delete()

Boolean

Delete a file.

exists()

Boolean

Check if the file exists.

getName()

String

Retrieve the name of the file.

getAbsolutePath()

String

Retrieve the absolute pathname of the file.

length()

Long

Retrieve the size of the file in bytes.

list()

String[]

Retrieve an array containing files in the directory.

mkdir()

Boolean

Create a directory.

In the upcoming chapters, you’ll discover how to create, write to, read from, and delete files.