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 “” 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("");4. System.out.println("1::" + myFile.getAbsolutePath());5. 6. myFile = new File("foo\bar\baz\");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
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet