digitization, transformation, binary

This post talks about the File Class in Java, File class Structure in Java, Methods with the description of File Class.

File Class in Java

An instance of this class File represents a file or a directory on the host file system. A file is specified by a pathname that can either be an absolute pathname or a pathname relative to the current working directory. The pathname must follow the naming convention of the host platform. The File class is intended to provide an abstraction that deals with most of the known machines dependent complexities of files and path names in a machine-independent manner.

The File class provides methods to obtain information about files and directories. A File object
encapsulates the name of a file or a directory. A File object can list the files in a directory, check the existence and type of a file, create new directories, and rename and delete files, among other things.

However, the File class does not handle I/O to files. Actual reading and writing is accomplished using RandomAccessFile, FileReader, FileWriter, FileInputStream, and
FileOutputStream objects.

The File class also defines some constants for the platform-specific directory and path separator characters. If we want to avoid putting system-dependent path information in our program, we may want to reference all files relative to the directory in which our program is running (i.e., the current directory). Alternatively, we can use java.awt.FileDialog to prompt the user for system-dependent paths.

Many of the methods in File throw a SecurityException if the application does not have sufficient privileges for the requested operation. This happens in two steps. First, System.getSecurityManager() is called. If a SecurityManager has been installed, it is queried for the appropriate permission.

For example, File.canRead() calls SecurityManager.canRead(). If the application does not have permission to read the specified file, the SecurityManager throws a SecurityException, which in turn is thrown by File.canRead().

A File object represents files that already exist or if we want to create one.

The File class structure as:

public class java.io.File extends java.lang.Object implements java.io.Serializable {
//Member elements:
public final static String pathSeparator;//the system-dependent path separator String. This field is initialized to contain the value of System property.
public final static char pathSeparatorChar; //the system-dependent path separator char. This filed is initialized to contain the first character value of the system property. This character is often used to separate file names in a sequence of files given as a path list.
public final static String separator; //the system-dependent path separator String. This field is initialized to contain the value of System property.
public final static char separatorChar;//the system-dependent path separator character. This filed is initialized to
//contain the first character value of the system property. This character separates the directory and file components in a filename.
//constructors:
public File(File dir, String name); //creates a file instance that represents the file with the specified name in the specified directory. If the directory argument is null, the resulting file instance represents a File in the system dependent current directory whose pathname is the pathname of the directory, followed by the separator character, followed by name argument.
public File(String path);//creates a file instance that represents the file whose pathname is the given argument. It may throw NullPointerException if the file path is equal to null.
public File(String path,String name);//creates a file instance that represents the file whose pathname is the pathname of the specified directory followed by the separator character followed by the name argument.
public File(URI uri);//Creates a new File instance by converting the given file URI into an abstract pathname.
//Methods:
public boolean canRead();//returns true if the file readable,false otherwise
public boolean canWrite();//returns true if the file is writable,false otherwise
public boolean delete();//returns true if the file is successfully deleted.This 
//only operates on simple file object It can not delete an empty directory.
public boolean equals(Object obj);
public boolean exists();//returns true if the file exists, false otherwise
public native boolean isAbsolute();//returns true if the file is with in the system false if it is relative.
public boolean isDirectory();//returns true if directory is a directory object,false otherwise
public boolean isFile();//returns true if the object is a file,false otherwise
public boolean mkdir();//this method creates the directory,returns true if successful.False indicate that the path specified in the file object already exists or the directory can not be created because the path does not exist.
public boolean mkdirs();//this will return true after creating where path of the directory may not exist.It not only creates a directory but also will create the parents of the directory.
public int compareTo(File pathname)//Compare two files path lexicographically.
public boolean renameTo(File destFileName);//returns true if the operation is successful and false if one of the cases happens-1. File does not exist 2. Filename is the same as renamed one.
public String getAbsolutePath();//returns the absolute path of a file when it is not in local
public String getName();//returns the name of the file object
public String getParent();//returns the parent directory in which the file object exists
public String getPath();//returns the path of the file object
public String[] list();//returns the list of all files in a directory.
public String[] list(FilenameFiler filter);
public File[] listFiles();//Returns the list of the files in an array of the current directory.
public static File createTempFile(String prefix, String suffix)//creates a temporary file in the default directory.
public long lastModified();//returns the date of the last modification in long format
public long length();//returns the length of the file
public boolean canExecute();// checks if the file is executable. If it is it returns true,false otherwise.
public boolean setExecutable(boolean executable); //Sets owner's executable permission to a file.
public boolean setReadable(boolean readable); //sets the owner's read permission.
public File getParentFile();//returns the parent file path of the current file.
public boolean createNewFile();// creates a new file if it does not there already.
public long getFreeSpace();//returns the free space  in the portion.
public boolean isHidden();//Returns true if the file is hidden,false otherwise.
public boolean setReadable(boolean readable, boolean ownerOnly); //sets owner or everybody's read permission.
public boolean setReadOnly(); //sets the file or directory for read permission.
public boolean setWritable(boolean writable); //Sets owner;s write permission.
public URI toURI(); // returns a file URI.
public int hashCode();
public String toString();
public String getCanonicalPath() throws IoException;
}

The details of the class structure are given as follows:

public final static String pathSeparator

public final static String pathSeparator is a string that holds the value of System.getProperty(‘path.separator’). It contains the character that separates paths in a path list. Usually, it is “:” or “;”.

public final static char pathSeparatorChar

public final static char pathSeparatorChar holds the first (and only) character in pathSeparator.

public final static String separator

public final static String separator  holds the value of System.getProperty(‘file.separator’). It contains the character that separates directory and filenames in a path string. Usually, it is “/” or “\”.

public final static char separatorChar

public final static char separatorChar holds the first (and only) character in the separator.

public File(File dir, String name)

public File(File dir, String name) constructor creates a File object that represents the file with the specified name in the directory described by the File object dir. In other words, the full pathname is the directory represented by dir, followed by the separator character, followed by the filename.

READ  How to Create Executable or Normal Jar File in Java?

If dir is null, the constructor creates a File that represents the file with the specified name in the current directory. The current directory is the directory in which the program is running.
Parameter
dir – A File object that represents a directory.
name – A filename.

public File(String path)

public File(String path) constructor creates a File object that represents the file specified by path.
Parameter
path – A full pathname (i.e., a directory and filename).

public File(String path,String name)

public File(String path, String name) constructor creates a File object that represents the file with the specified name in the directory described by the path. In other words, the full pathname is the directory, followed by the separator character, followed by the filename.

If the path is null, the constructor creates a File that represents the file with the specified name
in the current directory. The current directory is the directory in which the program is running.
Parameter
path – A directory path.
name – A filename.

public File(URI uri) 

public File(URI uri) constructor creates a new File instance by converting the given file URI into an abstract pathname.
Parameter
uri – An URL

public boolean canRead()

public boolean canRead() method returns true if File corresponds to an existing, readable file or directory.Otherwise it returns false.
This method returns a boolean value that indicates if the file is readable.

public boolean canWrite()

public boolean canWrite() method returns true if File corresponds to an existing, writable file or directory. Otherwise, it returns false.
This method returns a boolean value that indicates if the file is writable.

public boolean delete()

public boolean delete() method attempts to delete the file or directory associated with this File object. A directory
is only deleted if it is empty.
This method returns true if the file is deleted; otherwise false.

public boolean equals(Object obj)

public boolean equals(Object obj) method returns true if obj is an instance of File that encapsulates the same pathname as this object.
This method returns true if the objects are equal; false if they are not.
Parameter
obj – The Object to be compared.

public boolean exists()

public boolean exists() method returns true if this File corresponds to an existing file or directory.
This method returns true if the file or directory exists; false otherwise.

public native boolean isAbsolute()

public native boolean isAbsolute() method returns true if the file is with in the system false if it is relative.It indicates if the File represents an absolute path; what constitutes an absolute path is system-dependent.
This method returns true if the File represents an absolute path; false otherwise.

public boolean isDirectory()

public boolean isDirectory() method returns true if this File corresponds to a directory.
This method returns true if the File represents a directory; false otherwise.

public boolean isFile()

public boolean isFile() method returns true if this File corresponds to a normal file, as opposed to an alternative,
such as a directory, a named pipe, or a device.
This method returns true if the File represents a normal file; false otherwise.

public boolean mkdir()

public boolean mkdir() method creates a directory with the pathname specified by this File.
This method returns true if the directory is created; false otherwise.

public boolean mkdirs()

public boolean mkdirs() method creates a directory with the pathname specified by this File. The method also
creates all the parent directories if necessary.
This method returns true if the directory is created; false otherwise.

public int compareTo(File pathname)//Compare two files path lexicographically.

public int compareTo(File pathname)//Compare two files path lexicographically method
This method returns
Parameter

public boolean renameTo(File destFileName)

public boolean renameTo(File destFileName) method changes the pathname of this File to the pathname specified by destFileName.
This method returns true if the name is changed; false otherwise.
Parameter
destFileName – A File that specifies the new name.

public String getCanonicalPath()

public String getCanonicalPath() method returns the canonical pathname of the file or directory associated with this File.
This method returns a String that contains the canonical, or exact, pathname.

public String getAbsolutePath()

public String getAbsolutePath() method returns the absolute pathname of the file or directory associated with this File.
This method returns a String that contains the absolute pathname.
Parameter

public String getName()

public String getName() method returns the filename associated with this File. The string returned does not include the name of the directory.
This method returns a String that contains the filename.

public String getParent()

public String getParent() method returns the name of the parent directory of the file or directory associated with this File. The algorithm used returns everything in the pathname before the last separator character.
This method returns a String that contains the parent directory of the file, or null if it does not exist.

public String getPath()

public String getPath() method returns the full pathname associated with this File.
This method returns a String that contains the pathname of the file.

public String[] list()

public String[] list() method returns the contents of a directory. The current directory and the parent directory are
not included in the list.
This method returns an array of the names of the files and directories contained by this File, or null if this File is not a directory.

public String[] list(FilenameFiler filter)

public String[] list(FilenameFiler filter) method returns of the contents of a directory as selected by the given FilenameFilter object. Specifically, a name is included if the FilenameFilter object’s accept() method
returns true for that name.

READ  Class DataOutputStream in Java

If the filter is null, this method is equivalent to but slower than, list().

This method returns an array of the names of the files and directories contained by this File and filtered by the filter,
or null if this File is not a directory.
Parameter
filter – A filter to use.

public File[] listFiles()

public File[] listFiles( method
This method returns
Parameter

public static File createTempFile(String prefix, String suffix)//creates a temporary file in the default directory.

public static File createTempFile(String prefix, String suffix)//creates a temporary file in the default directory method
This method returns
Parameter

public long lastModified()

public long lastModified() method returns the modification time of the file or directory that corresponds to this File.

The format of the time returned is useful for comparing modification times; it’s not meant to be used for other purposes.
This method returns the time the file was last modified, or 0L if the file does not exist.

public long length()

public long length() method returns the length of the file or directory that corresponds to this File.
This method returns the file length, in bytes, or 0L if the file does not exist.
Parameter

public boolean canExecute()

public boolean canExecute() method checks if the file is executable. If it is it returns true, false otherwise.
This method returns true if the file is executable, false otherwise.

public boolean setExecutable(boolean executable)

public boolean setExecutable(boolean executable) method Sets owner’s executable permission to a file.
This method returns true if the permission is successful, false otherwise

public boolean setReadable(boolean readable)

public boolean setReadable(boolean readable) method sets the owner’s read permission.
This method returns true if the permission is successful, false otherwise

public File getParentFile()

public File getParentFile() method returns the parent file path of the current file.
This method returns the parent file path of the current file.

public boolean createNewFile()

public boolean createNewFile() method creates a new file if it does not there already.
This method returns true if the file created false otherwise.

public long getFreeSpace()

public long getFreeSpace() method returns the free space in the portion.
This method returns the free space in the portion.

public boolean isHidden()

public boolean isHidden() method returns true if the file is hidden,false otherwise.
This method returns true if the file is hidden, false otherwise.

public boolean setReadable(boolean readable, boolean ownerOnly)

public boolean setReadable(boolean readable, boolean ownerOnly) method sets owner or everybody’s read permission
This method returns true if it can able to set everybody’s read permission, false otherwise.

public boolean setReadOnly()

public boolean setReadOnly() method sets the file or directory for read permission.
This method returns true if it is able to set read permission for file or directory, false otherwise.

public boolean setWritable(boolean writable)

public boolean setWritable(boolean writable) method Sets owner’s write permission
This method returns true if it is able to set the owner’s write permission, false otherwise.

public URI toURI()

public URI toURI() method returns a file URI.
This method returns a file URI.

public int hashCode()

public int hashCode() method returns a hashcode based on the pathname associated with this File.
This method returns a hashcode value for this file.

public String toString()

public String toString() method returns a string representation of this File object.
This method returns a String that contains the pathname of this File.

READ  How Java is Platform Independent Language?

Apart from these File class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

How to Create an instance of File?

File fileName=new File(path of the file with extension).

While providing the path of the file backslash characters(\\) works well and acts as a path separator in windows. But for Linux, we need to use forward-slash(/)

An Example


public class MyFileTest{
public static void main(String []args) throws IOException{
File fileToCheck;
if(args.length>0)
{
for(int i=0;i<args.length;i++)
{
fileToCheck=new File(args[i]);
getNames(fileToCheck);
getInfo(fileToCheck);
}
}
else{
System.out.println("File error")
}
}
public static void getName(File f) throws IOException{
System.out.println("Name"+f.getName());
System.out.println("Path"+f.getPath());
System.out.println("Parent"+f.getParent());
}
public static void getInfo(File f) throws IOException{
if(f.exists)
{
System.out.println("File Exists");
}
else
{
System.out.println("File does not Exists");
}
if(f.canRead())
{
System.out.println("File is readable");
System.out.println("File last modified by"+f.lastModified());
System.out.println("File is"+f.length()+"bytes");
}
else{
System.out.println("File is not readable");
}
if(f.canWrite())
{
System.out.println("File is writeable");
}
else
{
System.out.println("File is not writable")
}
}
}
}

File class does not allow us to read or write to a file.To read or write we have other classes like

So in a nutshell, in Java, files are represented by File class that is part of the java.io package. Files can be placed or written to hard drives or other storage devices and can be accessed or read from this storage along with CDROM.File class Structure in Java(Methods with the description of File Class) is specified as above which helps us to design file operations.

LEAVE A REPLY

Please enter your comment!
Please enter your name here