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


The method pathCompinent() is used to remove the file information from a filename and return only its path component. This method requires a single parameter i.e. the file name and it returns the path 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 pathComponent(String fname) {
      int pos = fname.lastIndexOf(File.separator);
      if (pos > -1)
         return fname.substring(0, pos);
      else
         return fname;
   }
   public static void main(String[] args) {
      System.out.println(pathComponent("c:\JavaProgram\demo1.txt"));
   }
}

The output of the above program is as follows −

Output

c:\JavaProgram

Now let us understand the above program.

The method pathCompinent() is used to remove the file information from a file name and return only its path component. A code snippet that demonstrates this is given as follows −

public static String pathComponent(String fname) {
   int pos = fname.lastIndexOf(File.separator);
   if (pos > -1)
      return fname.substring(0, pos);
   else
      return fname;
}

The method main() prints the path component of the file name that was returned by the method pathComponent(). A code snippet that demonstrates this is given as follows −

public static void main(String[] args) {
   System.out.println(pathComponent("c:\JavaProgram\demo1.txt"));
}

Updated on: 30-Jul-2019

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements