Java Program to remove path information from a filename returning only its file component

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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"));
}
raja
Published on 25-Feb-2019 12:03:05
Advertisements