Friday, November 14, 2025
HomeLanguagesJavaJava File Class toString() Method with Examples

Java File Class toString() Method with Examples

This method returns the pathname string of the File object is returned by the function toString() function. This method is the same as calling the Java IO getPath() method.

Package view is as follows:

--> java.io Package
    --> File Class
        --> toString() Method   

Syntax:

public String toString()

Return Type: A string form of this abstract pathname.

Exceptions Thrown: SecurityException is thrown when we don’t have access to a file or directory.

Implementation: Prints the results of the function toString() function on numerous File objects in this example code.

  • Create file instance new File(“GeeksForGeeks.txt”);
  • file.toString(); It will convert the specified pathname into the string.

Example:

Java




// Java Program to Illustrate toString() Method
// of File Class
  
// Importing required classes
import java.io.File;
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Try block to check for exceptions
        try {
  
            // Creating a file
            File file = new File("GeeksForGeeks.txt");
            File txt = new File("./GeeksForGeeks.txt");
  
            System.out.println(file.toString());
            System.out.println(txt.toString());
        }
  
        // Catch block to handle the exceptions
        catch (Exception e) {
  
            // Display exception with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}


Output: Generated on Powershell/ Terminal

RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS