coderz.py

Keep Coding Keep Cheering!

File class in Java

java thread class

The File class represents a file or directory path name in Java. Because file and directory names differ between platforms, naming them with a simple string is insufficient. The File class is used to create files and directories, search for files, delete files, and so on.

Fields of File Class
ModifierTypeFieldDescription
staticStringpathSeparatorIt is a path-separator character that is system-dependent and is represented as a string for convenience.
staticcharpathSeparatorCharIt is a path-separator character that is system-dependent.
staticStringseparatorIt is the system’s default name-separator character, which is represented as a string for convenience.
staticcharseparatorCharIt is system-dependent default name-separator character.
Constructors of File Class:
ConstructorDescription
File(File parent, String child)It creates a new File instance from a parent abstract pathname and a child pathname string.
File(String pathname)It creates a new File instance by converting the provided pathname string to an abstract pathname.
File(String parent, String child)Furthermore, it constructs a new File instance from a parent and a child pathname string.
File(URI url)It generates a new File instance by converting the provided file: url to an abstract pathname.
Methods of File class:
Method Description
public String getName()Returns the name of the file or directory denoted by this abstract pathname.
public String getParent()Returns the pathname string of this abstract pathname’s parent directory, or null if this pathname has no parent directory.
public File getParentFile()Returns the abstract pathname of this abstract pathname’s parent, or null if this pathname does not name a parent directory.
public String getPath()Converts this abstract pathname into a pathname string.
public boolean isAbsolute()Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise.
public String getAbsolutePath()Returns the absolute pathname string of this abstract pathname.
public boolean canRead()Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise.
public boolean canWrite()Test whether the application can modify the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
public boolean exists()Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
public boolean isDirectory()Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.
public boolean isFile()Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.
public long lastModified()Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
public long length()Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
public boolean createNewFile() throws IOExceptionAtomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.
public boolean delete()Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.
public void deleteOnExit()Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
public String[] list()Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
public String[] list(FilenameFilter filter)Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfies the specified filter.
public File[] listFiles()Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
public File[] listFiles(FileFilter filter)Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfies the specified filter.
public boolean mkdir()Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.
public boolean mkdirs()Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.
public boolean renameTo(File dest)Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise.
public boolean setLastModified(long time)Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise.
public boolean setReadOnly()Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.
public static File createTempFile(String prefix, String suffix, File directory) throws IOExceptionCreates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.
public static File createTempFile(String prefix, String suffix) throws IOExceptionCreates an empty file in the default temporary file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.
public int compareTo(File pathname)Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
public int compareTo(Object o)Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
public boolean equals(Object obj)Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.
public String toString()Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.
Creating a File:

To create a file, we use the createNewFile() method, which takes a filename as an argument. If the file does not already exist, this method creates it.

import java.io.*;  
public class Coderz {  
    public static void main(String[] args) {  
  
        try {  
            File file = new File("File1.txt");  
            if (file.createNewFile()) {  
                System.out.println("New File is created!");  
            } else {  
                System.out.println("File already exists.");  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  
}  
Output:
New File is created!
Writing in a file:

A method of the Filewriter class is used to write data. It will write the data but may throw an exception, therefore the exceptions need to be handled.

import java.io.FileWriter; 
 // Import the IOException class to handle errors
import java.io.IOException; 
 
public class Coderz
{
   public static void main(String[] args) 
   {
     try
     {
       FileWriter myWriter = new FileWriter("D:File1.txt");
        // Writes this content into the specified file
        myWriter.write("Java is the prominent programming language of the millenium!"); 
        // Closing is necessary to retrieve the resources allocated
       myWriter.close(); 
       System.out.println("Successfully wrote to the file.");
    }
    catch (IOException e) 
    {
       System.out.println("An error occurred.");
       e.printStackTrace();
    }
 }
}
Output:
Successfully wrote to the file.
Reading a file:

To read data from a file, we used the File and Scanner classes, which are used to handle system resource input and output.

// Import the File class
import java.io.File; 
 // Import this class to handle errors
import java.io.FileNotFoundException; 
 // Import the Scanner class to read text files
import java.util.Scanner; 
 
public class ReadFromFile 
{
   public static void main(String[] args)
   {
       try
       {
       // Creating an object of the file for reading the data
       File myObj = new File("D:File1.txt");  
       Scanner Reader = new Scanner(myObj);
       while (Reader.hasNextLine()) 
       {
       String data = Reader.nextLine();
       System.out.println(data);
       }
      Reader.close();
   }
       catch (FileNotFoundException e) 
       {
          System.out.println("An error occurred.");
         e.printStackTrace();
       }
  }
}
Output:
Java is the prominent programming language of the millenium!
Copying a file:

Although Java provides built-in methods to directly copy one file data to another file, we will see a procedure to copy one file data to another.


import java.io.*;

// Main Class
public class Coderz {

	// Main driver method
	public static void main(String[] args)
		throws IOException
	{

		// Creating two stream
		// one input and other output
		FileInputStream fis = null;
		FileOutputStream fos = null;

		// Try block to check for exceptions
		try {

			// Custom directory path on local machine
			fis = new FileInputStream(
				"D:File1.txt");

			// Custom directory path on local machine
			fos = new FileOutputStream(
				"D:File2.txt");

			int c;

		
			while ((c = fis.read()) != -1) {

				// Writing to output file of the specified
				// directory
				fos.write(c);
			}

			
			System.out.println(
				"copied the file successfully");
		}

	
		finally {

			// Closing the streams

			if (fis != null) {

				// Closing the fileInputStream
				fis.close();
			}
			if (fos != null) {

				// Closing the fileOutputStream
				fos.close();
			}
		}
	}
}
Output:
copied the file successfully
Deleting a file:

To delete a file in Java, simply use the delete() method.

// Java program to delete a file
import java.io.*;

public class Test {
	public static void main(String[] args)
	{
		File file
			= new File("C:\\Users\\Mayank\\Desktop\\1.txt");

		if (file.delete()) {
			System.out.println("File deleted successfully");
		}
		else {
			System.out.println("Failed to delete the file");
		}
	}
}
Output:
File deleted successfully
Retrieving file information:

Obtaining metadata for a file is required in order to save information about the file such as its type, location, and permissions.

package FileHandling;
import java.io.File; // Import the File class
 
public class Coderz
{
   public static void main(String[] args)
   {
      // Creating an object of a file
      File Obj = new File("File1.txt");
      if (Obj.exists()) 
        {
           // Returning the file name
           System.out.println("File name: " + Obj.getName());
 
           // Returning the path of the file 
           System.out.println("Absolute path: " + Obj.getAbsolutePath());   
 
           // Displaying whether the file is writable
           System.out.println("Writeable: " + Obj.canWrite());  
 
           // Displaying whether the file is readable or not
           System.out.println("Readable " + Obj.canRead());  
 
            // Returning the length of the file in bytes
           System.out.println("File size in bytes " + Obj.length());  
       }
     else 
     {
        System.out.println("The file does not exist.");
     }
  }
}
Output:
File name: File1.txt
Absolute path: D:File1.txt
Writable: true
Readable true
File size in bytes 52
File permissions:

The following are the most important aspects of File Permission.

  • The actions to be granted are specified in a string that contains a list of one or more comma-separated keywords. The keywords “read,” “write,” “execute,” and “delete” are all possibilities.
  • The code can always read a file from the same directory (or a subdirectory of that directory); no explicit permission is required.

import java.io.*;

public class Coderz {
    public static void main(String[] args) {
        File fobj = new File("File1.txt");

        boolean bol = fobj.exists();
        if (bol == true) {
            System.out.println("Executable: " + fobj.canExecute());
            System.out.println("Readable: " + fobj.canRead());
            System.out.println("Writable: " + fobj.canWrite());
        } else {
            System.out.println("File not found.");
        }
    }
}
	
Output:
Executable: true
Readable: true
Writable: true

Note: also read about the Inner class in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement