Positioned within the java.io bundle, the Java File class is Java’s illustration of a file or listing pathname. It accommodates a number of strategies for working with the pathname, deleting and renaming recordsdata, creating new directories, itemizing the contents of a listing, and figuring out frequent attributes of recordsdata and directories. This tutorial will cowl different features of the File class together with tips on how to instantiate one, the totally different path varieties, getting details about a file, itemizing recordsdata, and dealing with recordsdata.
Easy methods to Create a File Object in Java
In a tutorial I wrote for TechRepublic (Listing Navigation in Java), we handed an absolute file path to the constructor, as proven within the following code instance:
File file = new File("C:My Paperwork");
The code above creates an summary illustration of the Home windows “My Paperwork” folder – additionally known as an summary pathname.
Builders may also consult with a file as follows:
// Utilizing a relative path File linuxFile = new File("/Java/myfile.csv"); // Utilizing an absolute path File windowsFile = new File("F:Javamyfile.txt");
The File class has just a few different constructors that we didn’t use. Here’s a description of these:
- File(File guardian, String youngster): Creates a brand new File occasion from a guardian File and a toddler pathname string.
- File(String guardian, String youngster): Creates a brand new File occasion from a guardian pathname string and a toddler pathname string.
- File(URI uri): Creates a brand new File occasion by changing the given file URI into an summary pathname.
Learn: Java Thread Class
Java Relative Pathnames
As denoted by the identify, a relative pathname is interpreted by way of info taken from another pathname. This info is obtained from the present listing of your program. The relative pathname is then mixed with the present listing path with a purpose to discover the requested file. In case you are ever uncertain what the present listing is, you could find out by calling the System.getProperty() methodology:
System.getProperty("person.dir");
Easy methods to Get Details about a Java File Object
As soon as a programmer has instantiated a brand new File object, they’ll acquire loads of details about it. Here’s a listing of strategies that may assist with that:
- public String getName(): Returns the identify of the file or listing denoted by this summary pathname.
- public String getParent(): Returns the pathname string of this summary pathname’s guardian, or null if this pathname doesn’t identify a guardian listing.
- public File getParentFile(): Returns the summary pathname of this summary pathname’s guardian, or null if this pathname doesn’t identify a guardian listing.
- public String getPath(): Converts this summary pathname right into a pathname string.
- public boolean isAbsolute(): Assessments whether or not this summary pathname is absolute. Returns true if this summary pathname is absolute, false in any other case.
- public String getAbsolutePath(): Returns absolutely the pathname string of this summary pathname.
- public String getCanonicalPath(): Returns the Canonical pathname of this summary pathname. If the pathname of the file object is Canonical then it merely returns the trail of the present file object. The Canonical path is at all times absolute and distinctive, the perform removes the ‘.‘ and ‘..‘ from the trail, if current.
- public boolean canRead(): Assessments whether or not the appliance can learn the file denoted by this summary pathname. Returns true if and provided that the file specified by this summary pathname exists and might be learn by the appliance, or false in any other case.
- public boolean canWrite(): Assessments whether or not the appliance can modify to the file denoted by this summary pathname. Returns true if – and provided that – the file system truly accommodates a file denoted by this summary pathname and the appliance is allowed to write down to the file; false in any other case.
- public boolean exists(): Assessments whether or not the file or listing denoted by this summary pathname exists. Returns true if and provided that the file or listing denoted by this summary pathname exists, or false in any other case.
- public boolean isDirectory(): Assessments whether or not the file denoted by this summary pathname is a listing. Returns true if and provided that the file denoted by this summary pathname exists and is a listing, or false in any other case.
- public boolean isFile(): Assessments whether or not the file denoted by this summary pathname is a standard file. A file is regular if it’s not a listing and, as well as, satisfies different system-dependent standards. Any non-directory file created by a Java software is assured to be a standard file. Returns true if – and provided that – the file denoted by this summary pathname exists and is a standard file, or false in any other case.
- public lengthy lastModified(): Returns the time that the file denoted by this summary pathname was final modified. Returns an extended worth representing the time the file was final modified, measured in milliseconds for the reason that epoch (00:00:00 GMT, January 1, 1970), or 0L if the file doesn’t exist or if an I/O error happens.
- public lengthy size(): Returns the size of the file denoted by this summary pathname, in bytes. The return worth is unspecified if this pathname denotes a listing.
- public String toString(): Returns the pathname string of this summary pathname. This is identical string returned by the getPath() methodology.
This modified model of the primary program shows a lot of File properties:
bundle com.developer; import java.io.File; import java.io.IOException; public class GetFileInfoExample { public static void major(String[] args) throws IOException { // Retailer the identify of recordsdata and directories // in an array of Information. // Do not forget to flee the backslash character! File[] recordsdata = new File("C:My Paperwork").listFiles(); // Traverse by way of the recordsdata array for (File file : recordsdata) { // If a subdirectory is discovered, // print the identify of the subdirectory System.out.println("Is a Listing? " + file.isDirectory()); System.out.println("Is a File? " + file.isFile()); if (file.isDirectory()) { System.out.println("Listing: " + file.getName()); } else { // Print the file identify System.out.println("File: " + file.getName()); } System.out.println("Exists? " + file.exists()); System.out.println("Mother or father: " + file.getParent()); System.out.println("Path: " + file.getPath()); System.out.println("Is absolute? " + file.isAbsolute()); System.out.println("Absolute path: " + file.getAbsolutePath()); System.out.println("Caninocal path: " + file.getCanonicalPath()); System.out.println("Is readable? " + file.canRead()); System.out.println("Is writable? " + file.canWrite()); System.out.println("Is executable? " + file.canExecute()); System.out.println("Final modified: " + file.lastModified()); System.out.println("Size (in bytes): " + file.size()); } } }
Listed below are the properties of the primary couple of Information:
//File 1: Is a Listing? true Is a File? false Listing: AAMS Exists? true Mother or father: I:My Paperwork Path: I:My DocumentsAAMS Is absolute? true Absolute path: I:My DocumentsAAMS Caninocal path: I:My DocumentsAAMS Is readable? true Is writable? true Is executable? true Final modified: 1588454396994 Size (in bytes): 0 Is a Listing? true Is a File? false Listing: Addictive Drums Exists? true Mother or father: I:My Paperwork Path: I:My DocumentsAddictive Drums Is absolute? true Absolute path: I:My DocumentsAddictive Drums Caninocal path: I:My DocumentsAddictive Drums Is readable? true Is writable? true Is executable? true Final modified: 1075183575015 Size (in bytes): 0 //File 2: Is a Listing? true Is a File? false Listing: Angular Exists? true Mother or father: I:My Paperwork Path: I:My DocumentsAngular Is absolute? true Absolute path: I:My DocumentsAngular Caninocal path: I:My DocumentsAngular Is readable? true Is writable? true Is executable? true Final modified: 1535211679142 Size (in bytes): 0 Is a Listing? true Is a File? false Listing: angular-starter Exists? true Mother or father: I:My Paperwork Path: I:My Documentsangular-starter Is absolute? true Absolute path: I:My Documentsangular-starter Caninocal path: I:My Documentsangular-starter Is readable? true Is writable? true Is executable? true Final modified: 1539441641426 Size (in bytes): 0
Learn: IntelliJ IDEA Evaluate
Itemizing Information in Java
After all, we have now already seen listFiles() in motion in each of the above examples. For completeness, listed here are all the File strategies that return an inventory of recordsdata or pathnames:
- public String[] listing(): Returns an array of strings naming the recordsdata and directories within the listing denoted by this summary pathname.
- public String[] listing(FilenameFilter filter): Returns an array of strings naming the recordsdata and directories within the listing denoted by this summary pathname that fulfill the desired filter.
- public File[] listFiles(): Returns an array of summary pathnames denoting the recordsdata within the listing denoted by this summary pathname.
- public File[] listFiles(FileFilter filter): Returns an array of summary pathnames denoting the recordsdata and directories within the listing denoted by this summary pathname that fulfill the desired filter.
Easy methods to Work with Information in Java
The Java File class additionally accommodates a lot of strategies for making a bodily file or listing, in addition to for modifying and deleting them. They’re listed beneath:
- public boolean createNewFile() throws IOException: Atomically creates a brand new, empty file named by this summary pathname if and provided that a file with this identify doesn’t but exist. Returns true if the named file doesn’t exist and was efficiently created; false if the named file already exists.
- public boolean delete(): Deletes the file or listing denoted by this summary pathname. If this pathname denotes a listing, then the listing should be empty with a purpose to be deleted. Returns true if and provided that the file or listing is efficiently deleted, or false in any other case.
- public void deleteOnExit(): Requests that the file or listing denoted by this summary pathname be deleted when the digital machine terminates.
- public boolean mkdir(): Creates the listing named by this summary pathname. Returns true if and provided that the listing was created, or false in any other case.
- public boolean mkdirs(): Creates the listing named by this summary pathname, together with any obligatory however nonexistent guardian directories. Returns true if and provided that the listing was created, together with all obligatory guardian directories, or false in any other case.
- public boolean renameTo(File dest): Renames the file denoted by this summary pathname. Returns true if and provided that the renaming succeeded, or false in any other case.
- public boolean setLastModified(very long time): Units the last-modified time of the file or listing named by this summary pathname. Returns true if and provided that the operation succeeded, or false in any other case.
- public boolean setReadOnly(): Marks the file or listing named by this summary pathname in order that solely learn operations are allowed. Returns true if and provided that the operation succeeded, or false in any other case.
- public static File createTempFile(String prefix, String suffix, File listing) throws IOException: Creates a brand new empty file within the specified listing, utilizing the given prefix and suffix strings to generate its identify. Returns an summary pathname denoting a newly-created empty file.
- public static File createTempFile(String prefix, String suffix) throws IOException: Creates an empty file within the default temporary-file listing, utilizing the given prefix and suffix to generate its identify. Invoking this methodology is equal to invoking createTempFile(prefix, suffix, null). Returns summary pathname denoting a newly-created empty file.
- public int compareTo(File pathname): Compares two summary pathnames lexicographically. Returns zero if the argument is the same as this summary pathname, a worth lower than zero if this summary pathname is lexicographically (i.e. by dictionary order) lower than the argument, or a worth better than zero if this summary pathname is lexicographically better than the argument.
- public int compareTo(Object o): Compares this summary pathname to a different object. Returns zero if the argument is the same as this summary pathname, a worth lower than zero if this summary pathname is lexicographically lower than the argument, or a worth better than zero if this summary pathname is lexicographically better than the argument.
- public boolean equals(Object obj): Assessments this summary pathname for equality with the given object. Returns true if – and provided that – the argument will not be null and is an summary pathname that denotes the identical file or listing as this summary pathname.
Let’s give just a few of those strategies a strive. Right here is an instance program that creates a file within the present working listing, renames it, after which makes an attempt to delete each the unique and renamed file from the drive:
bundle com.developer; import java.io.File; import java.io.IOException; public class FileOperationsExample { public static void major(String args[]) { strive { // Creating an object of a file File testFile = new File("FileOperationsExample.txt"); if (testFile.createNewFile()) { System.out.println("File " + testFile.getName() + " is created efficiently."); System.out.println("Path is " + testFile.getAbsolutePath()); } else { System.out.println("File is exist already within the listing."); } File renamedTestFile = new File(" FileOperationsExampleRenamed. txt"); boolean renamed = testFile.renameTo( renamedTestFile); if (renamed) { System.out.println("File has been renamed to " + testFile.getName()); } else { System.out.println("Couldn't rename the File."); } boolean isDeleted = renamedTestFile.delete(); if (isDeleted) { System.out.println("The renamed take a look at file has been efficiently deleted."); } else { System.out.println("Couldn't delete the renamed take a look at file."); } // It will fail as a result of the testFile has been renamed isDeleted = testFile.delete(); if (isDeleted) { System.out.println("The take a look at file has been efficiently deleted."); } else { System.out.println("Couldn't delete the take a look at file."); } } catch (IOException exception) { System.out.println("An surprising error is occurred."); exception.printStackTrace(); } } }
Though we might delete the renamed file, the delete() failed on the unique file because it now not exists!
File FileOperationsExample.txt is created efficiently. Path is I:article-workspacedirectoryNavigation FileOperationsExample.txt File has been renamed to FileOperationsExample.txt The renamed take a look at file has been efficiently deleted. Couldn't delete the take a look at file.
Last Ideas on the Java File Class
On this programming tutorial, we discovered tips on how to instantiate a File, in regards to the totally different path varieties, tips on how to get details about a File, listing Information, and dealing with Information. You my have seen that the File class doesn’t include any strategies for studying or writing to a file. These are a part of a number of different lessons which might be organized by file sort, i.e. textual content versus binary, and the way they learn and/or write to it, i.e. one line at a time, utilizing a buffer, or all of sudden.
Learn: High Java Frameworks