Home Software Development Java File Class | Developer.com

Java File Class | Developer.com

0
Java File Class | Developer.com

[ad_1]

Developer.com content material and product suggestions are editorially unbiased. We might earn money once you click on on hyperlinks to our companions. Be taught Extra.

Java Programming tutorials

Positioned within the java.io package deal, 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 points of the File class together with tips on how to instantiate one, the totally different path sorts, getting details about a file, itemizing recordsdata, and dealing with recordsdata.

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 can even seek advice from 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 a couple of different constructors that we didn’t use. Here’s a description of these:

  • File(File father or mother, String youngster): Creates a brand new File occasion from a father or mother File and a toddler pathname string.
  • File(String father or mother, String youngster): Creates a brand new File occasion from a father or mother 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 title, a relative pathname is interpreted by data taken from another pathname. This data is obtained from the present listing of your program. The relative pathname is then mixed with the present listing path as a way to discover the requested file. In case you are ever not sure what the present listing is, yow will discover out by calling the System.getProperty() methodology:

System.getProperty("person.dir");

Methods to Get Details about  a Java File Object

As soon as a programmer has instantiated a brand new File object, they’ll receive numerous details about it. Here’s a record of strategies that may assist with that:

  • public String getName(): Returns the title of the file or listing denoted by this summary pathname.
  • public String getParent(): Returns the pathname string of this summary pathname’s father or mother, or null if this pathname doesn’t title a father or mother listing.
  • public File getParentFile(): Returns the summary pathname of this summary pathname’s father or mother, or null if this pathname doesn’t title a father or mother listing.
  • public String getPath(): Converts this summary pathname right into a pathname string.
  • public boolean isAbsolute(): Exams 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 all the time absolute and distinctive, the perform removes the ‘.‘ and ‘..‘ from the trail, if current.
  • public boolean canRead(): Exams whether or not the applying can learn the file denoted by this summary pathname. Returns true if and provided that the file specified by this summary pathname exists and may be learn by the applying, or false in any other case.
  • public boolean canWrite(): Exams whether or not the applying 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 applying is allowed to write down to the file; false in any other case.
  • public boolean exists(): Exams 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(): Exams 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(): Exams whether or not the file denoted by this summary pathname is a traditional file. A file is regular if it isn’t 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 traditional file. Returns true if – and provided that – the file denoted by this summary pathname exists and is a traditional 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 because the 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 similar string returned by the getPath() methodology.

This modified model of the primary program shows quite a lot of File properties:

package deal com.developer;

import java.io.File;
import java.io.IOException;

public class GetFileInfoExample {
  public static void important(String[] args) throws IOException {
    // Retailer the title of recordsdata and directories
    // in an array of Recordsdata.
    // Remember to flee the backslash character!
    File[] recordsdata = new File("C:My Paperwork").listFiles();
    
    // Traverse by the recordsdata array
    for (File file : recordsdata) {
      // If a subdirectory is discovered,
      // print the title 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 title
        System.out.println("File: " + file.getName());
      }
      System.out.println("Exists? " + file.exists());
      System.out.println("Mum or dad: " + 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 here are the properties of the primary couple of Recordsdata:

//File 1:
Is a Listing? true
Is a File? false
Listing: AAMS
Exists? true
Mum or dad: 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
Mum or dad: 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
Mum or dad: 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
Mum or dad: 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 Assessment

Itemizing Recordsdata in Java

After all, now we have already seen listFiles() in motion in each of the above examples. For completeness, listed here are the entire File strategies that return a listing of recordsdata or pathnames:

  • public String[] record(): Returns an array of strings naming the recordsdata and directories within the listing denoted by this summary pathname.
  • public String[] record(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.

Methods to Work with Recordsdata in Java

The Java File class additionally accommodates quite a lot of strategies for making a bodily file or listing, in addition to for modifying and deleting them. They’re listed under:

  • 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 title 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 as a way 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 crucial however nonexistent father or mother directories. Returns true if and provided that the listing was created, together with all crucial father or mother 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 title. 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 title. 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 higher than zero if this summary pathname is lexicographically higher 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 higher than zero if this summary pathname is lexicographically higher than the argument.
  • public boolean equals(Object obj): Exams this summary pathname for equality with the given object. Returns true if – and provided that – the argument is just not null and is an summary pathname that denotes the identical file or listing as this summary pathname.

Let’s give a couple of 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:

package deal com.developer;

import java.io.File;
import java.io.IOException;

public class FileOperationsExample {
  public static void important(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 check file has been efficiently deleted.");
      } else {
        System.out.println("Couldn't delete the renamed check file.");
      }
      
      // It will fail as a result of the testFile has been renamed
      isDeleted = testFile.delete();
      if (isDeleted) {
        System.out.println("The check file has been efficiently deleted.");
      } else {
        System.out.println("Couldn't delete the check file.");
      }
    } catch (IOException exception) {  
      System.out.println("An surprising error is occurred.");  
      exception.printStackTrace();  
    }   
  }  
}

Though we may 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-workspacedirectoryNavigationFileOperationsExample.txt
File has been renamed to FileOperationsExample.txt
The renamed check file has been efficiently deleted.
Couldn't delete the check file.

Remaining Ideas on the Java File Class

On this programming tutorial, we realized tips on how to instantiate a File, in regards to the totally different path sorts, tips on how to get details about a File, record Recordsdata, and dealing with Recordsdata. You my have observed 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 courses which are 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 .

Learn: Prime Java Frameworks

[ad_2]