Menu
Topics Index
...
`
A File class in Java is an abstract representation of file and directory pathnames(e.g., c:/Programs/SampleFile.txt). Here Programs is a directory and SampleFile is a file.

The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file.
Examples :
C:\Program Files\Java
E:\Files\SampleFile.txt
hostname:/directorypath/resource
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Constructors :
Constructor Description
public File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
File(String parent, String child) Creates a new File instance from a parent pathname string and a child pathname string.
Important Methods
Method Description
boolean createNewFile() 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 exists() Tests whether the file or directory denoted by this abstract pathname exists.
boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file.
boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory.
boolean canExecute() Tests whether the application can execute the file denoted by this abstract pathname.
boolean canWrite() Tests whether the application can modify the file denoted by this abstract pathname.
boolean canRead() Tests whether the application can read the file denoted by this abstract pathname.
boolean setExecutable(boolean executable) This is a convenience method to set the owner's execute permission for this abstract pathname.
boolean setReadOnly() Marks the file or directory named by this abstract pathname so that only read operations are allowed.
boolean setWritable(boolean writable) This is a convenience method to set the owner's write permission for this abstract pathname.
String getPath() Converts this abstract pathname into a pathname string.
String getName() Returns the name of the file or directory denoted by this abstract pathname.
boolean delete() Deletes the file or directory denoted by this abstract pathname.
boolean mkdirs() Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
FileDemo
import java.io.*;

class CreatingFilesandFolders
{
    public static void main(String[] args) throws IOException
    {
        File folder = new File("E:JavaPrograms\\FolderOne\\"); // LINE A
    
        if(folder.mkdirs()) // LINE B
            System.out.println("Folder created.");
        else if(folder.exists()) // LINE C
            System.out.println("Folder already exists.");
        System.out.println(folder.getPath()); // LINE D
    
        File fileOne = new File(folder, "fileOne.txt"); // LINE E
        File fileTwo = new File(folder, "fileTwo.txt"); // LINE F
        
        if(fileOne.createNewFile() && fileTwo.createNewFile()) // LINE G
            System.out.println("Files created.");
        
        else if(fileOne.exists() && fileTwo.exists())
            System.out.println("files already exists");
        System.out.println(fileOne.getPath() + "\n" + fileTwo.getPath()); // LINE H
                                                                            
    }

}
OUTPUT

Folder created.
E:JavaPrograms\FolderOne
Files created.
E:JavaPrograms\FolderOne\fileOne.txt
E:JavaPrograms\FolderOne\fileTwo.txt

DESCRIPTION

At LINE A we are creating an absolute path string for folder.
At LINE B we are creating folder here mkdirs create folders and returns true if the folders are created otherwise false.
At LINE C we are checking whether the folder already exists.
At LINE D we are printing the path of folder.
At LINE E and LINE F we are creating absolute path for files.
At LINE G we are creating files using createNewFile.
At LINE H we are printing the file paths.

THINGS TO TRY
  • Create one more folder FolderTwo in JavaPrograms folder.
  • Create two more files fileThree and fileFour in FolderTwo.
FilePermissionsDemo
import java.io.*;

class FileOperationsDemo
{
    public static void main(String[] args) throws IOException
    {
        File sampleFile = new File("E:JavaPrograms\\FolderOne\\sampleFile.txt");
        if(sampleFile.createNewFile())                     // LINE A
            System.out.println("File created.");
        else
            System.out.println("File not created.");
        
        System.out.println("Default permissions for a newly created file.");
        System.out.println("IsFile        : " + sampleFile.isFile()); // LINE B
        System.out.println("CanRead    : " + sampleFile.canRead());    // LINE C
        System.out.println("CanWrite   : " + sampleFile.canWrite());   // LINE D
        System.out.println("CanExecute : " + sampleFile.canExecute()); // LINE E
    
        System.out.println("Changing file permissions.");
         // LINE F                                  
        System.out.println("Can set to non readable   : " + sampleFile.setReadable(false));
        // LINE G                                
        System.out.println("Can set to non writable   : " + sampleFile.setWritable(false));
        // LINE H                                
        System.out.println("Can set to non Executable : " + sampleFile.setExecutable(false));
    }
}
OUTPUT

File created.
Default permissions for a newly created file.
IsFile        : true
CanRead    : true
CanWrite   : false
CanExecute : true
Changing file permissions.
Can set to non readable   : false
Can set to non writable   : true
Can set to non Executable : false

DESCRIPTION

At LINE A we have created a sampleFile.
At LINE B we are checking whether sampleFile is a File or not.
At LINE C we are checking whether sampleFile is readable.
At LINE D we are checking whether sampleFile is writable.
At LINE E we are checking whether sampleFile is executable.
At LINE F we are checking whether we can set sampleFile to non readable.
At LINE G we are checking whether we can set sampleFile to non writable.
At LINE F we are checking whether we can set sampleFile to non executable.

THINGS TO TRY
  • Find the path of sampleFile using getPath method.
  • Delete sampleFile file.
Rest of Methods :
Method Description
int compareTo(File pathname) compares two abstract pathnames lexicographically.
static File createTempFile(String prefix, String suffix) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
static File createTempFile(String prefix, String suffix, File directory) Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.
void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
boolean equals(Object obj) Tests this abstract pathname for equality with the given object.
File getAbsoluteFile() Returns the absolute form of this abstract pathname.
String getAbsolutePath() Returns the absolute pathname string of this abstract pathname.
File getCanonicalFile() Returns the canonical form of this abstract pathname.
String getCanonicalPath() Returns the canonical pathname string of this abstract pathname.
long getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name.
String getParent() Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
File getParentFile() Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
long getTotalSpace() Returns the size of the partition named by this abstract pathname.
long getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.
int hashCode() Computes a hash code for this abstract pathname.
boolean isAbsolute() Tests whether this abstract pathname is absolute.
boolean isHidden() Tests whether the file named by this abstract pathname is a hidden file.
long lastModified() Returns the time that the file denoted by this abstract pathname was last modified.
long length() Returns the length of the file denoted by this abstract pathname.
String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
String[] list(FilenameFilter filter) Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
File[] listFiles(FileFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
File[] listFiles(FilenameFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
static File[] listRoots() lists the available filesystem roots.
boolean mkdir() Creates the directory named by this abstract pathname.
boolean renameTo(File dest) Renames the file denoted by this abstract pathname.
boolean setExecutable(boolean executable, boolean ownerOnly) Sets the owner's or everybody's execute permission for this abstract pathname.
boolean setLastModified(long time) Sets the last-modified time of the file or directory named by this abstract pathname.
boolean setReadable(boolean readable) This is a convenience method to set the owner's read permission for this abstract pathname.
boolean setReadable(boolean readable, boolean ownerOnly) Sets the owner's or everybody's read permission for this abstract pathname.
boolean setWritable(boolean writable, boolean ownerOnly) Sets the owner's or everybody's write permission for this abstract pathname.
String toString() Returns the pathname string of this abstract pathname.
URI toURI() Constructs a file: URI that represents this abstract pathname.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App