- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to remove path information from a filename returning only its file component
The method fileCompinent() is used to remove the path information from a filename and return only its file component. This method requires a single parameter i.e. the file name and it returns the file component only of the file name.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo { public static String fileComponent(String fname) { int pos = fname.lastIndexOf(File.separator); if(pos > -1) return fname.substring(pos + 1); else return fname; } public static void main(String[] args) { System.out.println(fileComponent("c:\JavaProgram\demo1.txt")); } }
The output of the above program is as follows −
Output
demo1.txt
Now let us understand the above program.
The method fileComponent() is used to remove the path information from a filename and return only its file component. A code snippet that demonstrates this is given as follows −
public static String fileComponent(String fname) { int pos = fname.lastIndexOf(File.separator); if(pos > -1) return fname.substring(pos + 1); else return fname; }
The method main() prints the file component of the file name that was returned by the method fileComponent(). A code snippet that demonstrates this is given as follows −
public static void main(String[] args) { System.out.println(fileComponent("c:\JavaProgram\demo1.txt")); }
- Related Articles
- Java Program to remove file information from a filename returning only its path component
- Get an Absolute Filename Path from a Relative Filename Path in Java
- Get an Absolute Filename Path from a Relative Filename with Path in Java
- Get filename from string path in JavaScript?
- How to get the last dirname/filename in a file path argument in Bash?
- Java Program to strip a filename of its extension after the last dot
- C program to remove a line from the file
- Get the path of the file selected in the JFileChooser component with Java
- Create a file and change its attribute to read-only in Java
- Java program to insert a component into a JTextPane component
- Java Program to create a file and sets it to read-only
- C# Program to get information about a file
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Java Program to remove a key from a TreeMap only if it is associated with a given value
- Java Program to remove a key from a HashMap

Advertisements