0% found this document useful (0 votes)
27 views7 pages

Java File Class Overview and Methods

The File class in Java represents files and directories in an abstract way. It provides methods to work with files and directories like creating, deleting, renaming, listing contents. The File class has fields, constructors and useful methods like createTempFile(), createNewFile(), canWrite(), canExecute(), canRead(), isAbsolute(), isDirectory(), isFile(), getName(), getParent(), toPath(), toURI(), listFiles(), getFreeSpace(), list() and mkdir().

Uploaded by

connectd77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views7 pages

Java File Class Overview and Methods

The File class in Java represents files and directories in an abstract way. It provides methods to work with files and directories like creating, deleting, renaming, listing contents. The File class has fields, constructors and useful methods like createTempFile(), createNewFile(), canWrite(), canExecute(), canRead(), isAbsolute(), isDirectory(), isFile(), getName(), getParent(), toPath(), toURI(), listFiles(), getFreeSpace(), list() and mkdir().

Uploaded by

connectd77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java File Class

ADVERTISEMENT

The File class is an abstract representation of file and directory pathname. A pathname can be either
absolute or relative.

The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.

Fields
ADVERTISEMENT

Modifier Type Field Description

static String pathSeparator It is system-dependent path-separator character,


represented as a string for convenience.

static char pathSeparatorChar It is system-dependent path-separator character.

static String separator It is system-dependent default name-separator


character, represented as a string for convenience.

static char separatorChar It is system-dependent default name-separator


character.
Constructors
ADVERTISEMENT

Constructor Description

File(File parent, String It creates a new File instance from a parent abstract pathname and a
child) child pathname string.

File(String pathname) It creates a new File instance by converting the given pathname string
into an abstract pathname.

File(String parent, String It creates a new File instance from a parent pathname string and a
child) child pathname string.

File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.

Useful Methods
ADVERTISEMENT

Modifier Method Description


and Type
static File createTempFile(String It creates an empty file in the default temporary-file
prefix, String suffix) directory, using the given prefix and suffix to
generate its name.

boolean createNewFile() It atomically creates a new, empty file named by this


abstract pathname if and only if a file with this name
does not yet exist.

boolean canWrite() It tests whether the application can modify the file
denoted by this abstract [Link][]

boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.

boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.

boolean isAbsolute() It tests whether this abstract pathname is absolute.

boolean isDirectory() It tests whether the file denoted by this abstract


pathname is a directory.

boolean isFile() It tests whether the file denoted by this abstract


pathname is a normal file.

String getName() It returns the name of the file or directory denoted


by this abstract pathname.

String getParent() It returns the pathname string of this abstract


pathname's parent, or null if this pathname does not
name a parent directory.

Path toPath() It returns a [Link] object constructed from


the this abstract path.

URI toURI() It constructs a file: URI that represents this abstract


pathname.

File[] listFiles() It returns an array of abstract pathnames denoting


the files in the directory denoted by this abstract
pathname

long getFreeSpace() It returns the number of unallocated bytes in the


partition named by this abstract path name.

String[] list(FilenameFilter filter) It returns an array of strings naming the files and
directories in the directory denoted by this abstract
pathname that satisfy the specified filter.
boolean mkdir() It creates the directory named by this abstract
pathname.

Java File Example 1

import [Link].*;
public class FileDemo {
public static void main(String[] args) {

try {
File file = new File("[Link]");
if ([Link]()) {
[Link]("New File is created!");
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]();
}

}
}

Output:

New File is created!

Java File Example 2

import [Link].*;
public class FileDemo2 {
public static void main(String[] args) {

String path = "";


boolean bool = false;
try {
// createing new files
File file = new File("[Link]");
[Link]();
[Link](file);
// createing new canonical from file object
File file2 = [Link]();
// returns true if the file exists
[Link](file2);
bool = [Link]();
// returns absolute pathname
path = [Link]();
[Link](bool);
// if file exists
if (bool) {
// prints
[Link](path + " Exists? " + bool);
}
} catch (Exception e) {
// if any error occurs
[Link]();
}
}
}

Output:

[Link]
/home/Work/Project/File/[Link]
true
/home/Work/Project/File/[Link] Exists? true

Java File Example 3

import [Link].*;
public class FileExample {
public static void main(String[] args) {
File f=new File("/Users/sonoojaiswal/Documents");
String filenames[]=[Link]();
for(String filename:filenames){
[Link](filename);
}
}
}

Output:

"[Link]"
"[Link]".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
[Link]
bestreturn_org.rtf
[Link]
[Link]
[Link]
[Link]
workspace

Java File Example 4

import [Link].*;
public class FileExample {
public static void main(String[] args) {
File dir=new File("/Users/sonoojaiswal/Documents");
File files[]=[Link]();
for(File file:files){
[Link]([Link]()+" Can Write: "+[Link]()+"
Is Hidden: "+[Link]()+" Length: "+[Link]()+" bytes");
}
}
}

Output:

"[Link]" Can Write: true Is Hidden: false Length: 15 bytes


"[Link]".rtf Can Write: true Is Hidden: false Length: 385 bytes
.DS_Store Can Write: true Is Hidden: true Length: 36868 bytes
.localized Can Write: true Is Hidden: true Length: 0 bytes
Alok news Can Write: true Is Hidden: false Length: 850 bytes
apache-tomcat-9.0.0.M19 Can Write: true Is Hidden: false Length: 476 bytes
[Link] Can Write: true Is Hidden: false Length: 13711360 bytes
bestreturn_org.rtf Can Write: true Is Hidden: false Length: 389 bytes
[Link] Can Write: true Is Hidden: false Length: 707985 bytes
[Link] Can Write: true Is Hidden: false Length: 69681 bytes
[Link] Can Write: true Is Hidden: false Length: 282125 bytes
workspace Can Write: true Is Hidden: false Length: 1972 bytes

← Prev Next →

Youtube For Videos Join Our Youtube Channel: Join Now

Feedback

Send your Feedback to feedback@[Link]

Help Others, Please Share

Learn Latest Tutorials

Splunk SPSS tutorial Swagger T-SQL


tutorial tutorial tutorial
SPSS
Splunk Swagger Transact-SQL

Tumblr React tutorial Regex


tutorial tutorial Reinforcement
ReactJS
learning
Tumblr Regex
tutorial
Reinforcement
Learning

R RxJS tutorial React Native Python


Programming tutorial Design Patterns
RxJS
tutorial
React Native Python Design
R Programming Patterns

Python Python Keras


Pillow tutorial Turtle tutorial tutorial
Python Pillow Python Turtle Keras

Common questions

Powered by AI

File visibility and size are checked using the 'isHidden()' and 'length()' methods, respectively. 'isHidden()' determines if a file is not visible due to system settings, while 'length()' returns the file size in bytes. These methods provide insights into the file's status and characteristics, useful for determining accessibility and storage requirements .

The Java File class differentiates an absolute pathname from a relative one based on its system representation. The 'isAbsolute()' method tests whether the abstract pathname is absolute, meaning it is complete and doesn't require resolution against another path .

Creating a 'File' object using a 'URI' is particularly useful when a Java application deals with files whose locations are specified by URIs, such as remote files or network-based resources. By integrating URI handling, applications can streamline operations across different file systems and network resources by converting the URI directly into a file path for processing .

The Java File class handles I/O operations with methods such as 'createNewFile', 'canRead', 'canWrite', and 'canExecute', which test a file's readability, writability, and executability to prevent exceptions. For instance, before attempting to write, 'canWrite' checks if modification is permissible, preventing attempts that could result in 'IOExceptions.' These methods enable safe and preemptive management of file operations .

The 'listFiles()' method returns an array of abstract pathnames denoting the files in the directory denoted by the abstract pathname, which implies that any operation performed on directories using this method requires iteration over the returned array. Handling directories with potential large numbers of files must consider performance impacts and memory constraints, as the method loads all file path objects into memory .

The 'createNewFile' method atomically creates a new, empty file named by this abstract pathname only if a file with this name does not already exist. The method returns true if the file was successfully created and false if the file already exists, which is crucial for ensuring that an existing file is not overridden .

The Java File class provides several constructors that differ in how they create a File instance. These include: File(File parent, String child) which creates a File instance using a parent abstract pathname and a child pathname string; File(String pathname) which uses a single pathname string; File(String parent, String child) which uses separate parent and child pathname strings; and File(URI uri) which converts a URI into an abstract pathname .

The 'pathSeparator' and 'separator' fields in the Java File class represent system-dependent characters used for separating directory paths ('pathSeparator') and file names ('separator'). They vary across systems: for instance, Windows uses '\\' as a separator, while Unix-based systems use '/' .

The 'createTempFile' method facilitates the creation of temporary files by allowing specification of a filename prefix and suffix, ensuring unique filenames are generated in the default temporary-file directory. As a safety measure, the method ensures files are created in a specific environment with restricted access, reducing the risk of conflict and unintended overwriting .

Recursive directory listing in Java can be facilitated using the 'listFiles()' method in conjunction with recursive functions. The primary challenge in large directories is performance, as it requires extensive processing to visit each file and subdirectory, potentially leading to memory overuse and stack overflow errors if not carefully managed with iteration and depth limits .

You might also like