devxlogo

Manipulating File Names With the File Class

Java defines a File class (see Tip: “Constructing a File Class”) that you can use to manipulate the file name and perform file-related operations on the underlying file system (see Tip: “Performing File Operations With the File Class”). Some useful methods for manipulating the file name, which is a text string, include:

 public String getAbsolutePath()  // Gets complete pathpublic String getName()          // Gets the file name (without path)public String getParent()        // Gets the parent directorypublic boolean isDirectory()     // Answers "is this File a directory?"public boolean isFile()          // Answers "is this File a file?"

The following code excerpt makes use of these methods. Assume that your system has a file “myfile.xyz” under the directory “C:fooaraz”. Also, assume that this code is running in the directory “C:fooaraz.”

 1. File myFile = null;2. 3. myFile = new File("myfile.xyz");4. System.out.println("1::" + myFile.getAbsolutePath());5. 6. myFile = new File("foo\bar\baz\myfile.xyz");7. System.out.println("2::" + myFile.getName());8. System.out.println("3::" + myFile.getParent());9. System.out.println("4::" + myFile.isFile());10. System.out.println("5::" + myFile.isDirectory());

The output of this code is:

 1::C:fooarazmyfile.txt2:: myfile.txt3::C:fooaraz4::true5::false

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.