Remove Path Information from a Filename in Java



In this article, we will learn to remove path information from a filename returning only its file component using Java. 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.

Problem Statement

Write a program in Java to remove path information from a filename returning only its file component ?

Input

"c:\JavaProgram\demo1.txt"

The input is the file path.

Output

demo1.txt

Steps to remove path information

Following are the steps to remove path information from a filename returning only its file component?

  • First we will import the java.io.File package.
  • After that we will define a fileComponent() method that takes a file path as a string.
  • Inside the method, locate the last occurrence of the path separator.
  • Extract the file name after the separator, or return the full string if no separator is found.
  • In the main() method, call the fileComponent() method with a file path as the argument.
  • Print the returned file name.

Java program to remove path information

A Java program that demonstrates how to remove path information from a filename returning only its file component is given as follows ?

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"));
   }
}

Output

demo1.txt

Code Explanation

In the above Java program, we will remove path information from a filename returning only its file component. The fileComponent() method finds the last position of the file path separator using lastIndexOf(). If the separator exists, it extracts the part after the separator using substring(), which represents the file name. If no separator is found, the original string is returned. In the main() method, this function is called with the path "c:\JavaProgram\demo1.txt", and the resulting file name, demo1.txt, is printed.

Updated on: 2024-10-10T11:38:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements