Java File Class Basics Notes
Java File Class Basics
Java File Class Overview
- Represents a file or directory pathname.
Capabilities of the Java File Class
- Can delete, rename files, create directories, and list directory contents.
Abstract Pathname
- It is a representation of files and directory pathnames.
Creating a File Object
- Initialization
- Create a File object by passing a filename or directory name as a string.
Common Methods of the Java File Class
getParent()
- Returns the parent of an abstract pathname.
exists()
- Checks if a file or directory physically exists.
isDirectory()
- Checks if the pathname is a directory.
length()
- Returns the size of the file in bytes.
getName()
- Returns the name of the file.
list()
- Returns an array of strings representing filenames in a directory.
canRead() vs canWrite()
- canRead(): Checks if the file can be read.
- canWrite(): Checks if the file can be written to.
Java Constructors and File Methods
Constructor
- A special method used to initialize objects.
createNewFile()
- Creates a new, empty file.
delete()
- Deletes the file or directory.
getAbsolutePath()
- Returns the absolute pathname as a string.
Path Separators and File vs Directory
Path Separator
- Character used to separate individual paths (e.g., in Windows, it's
\, in Unix/Linux, it's/).
- Character used to separate individual paths (e.g., in Windows, it's
Difference Between File and Directory
- File: A single file storing data.
- Directory: Can contain multiple files and other directories.
Additional File Methods
isFile()
- Checks if the pathname is a normal file.
mkdir()
- Creates a new directory.
renameTo()
- Renames a file or directory.
toString()
- Returns the pathname string of the abstract pathname.
isHidden()
- Checks if the file is marked as hidden.
Main Use of the File Class
- The primary purpose of the File class in Java is to work with files and directories, enabling operations such as creation, deletion, reading, and writing data.