String class methods to separate file path, name and extension – Computer Sir Ki Class


Lost your password?

Don't have an account ?
Register (It's FREE) ×


Exam Questions-ICSE2014-06A #JAVA#7428    siteicon   siteicon  

Problem Statement - String class methods to separate file path, name and extension

Write a program to assign a full path and file name as given below. Using library functions, extract and output the file path, file name and
file extension separately as shown.
Input C:\Users\admin\Pictures\flower.jpg
Output Path: C:\Users\admin\Pictures\
File name: flower
Extension: jpg


TC++ #7428

import java.util.Scanner;

 public class FileName {

 public static void main(String[] args) {
 Scanner scanner = new Scanner(;
 System.out.print("Enter file name and path: ");
 String input = scanner.nextLine();
 int indexOfLastBackslash = input.lastIndexOf('\\');
 int indexOfDot = input.lastIndexOf('.');
 String outputPath = input.substring(0, indexOfLastBackslash + 1);
 String fileName = input.substring(indexOfLastBackslash + 1, indexOfDot);
 String extension = input.substring(indexOfDot + 1);
 System.out.println("Path: " + outputPath);
 System.out.println("File Name: " + fileName);
 System.out.println("Extension: " + extension);


CSKC| Created: 18-Apr-2019 | Updated: 25-Nov-2019|ICSE2014