QuesAns Print Page – CSKC
Sign In

Search

siteicon
Q&A ICSE2014-06A #7428

Question:

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

Answer:

import java.util.Scanner;

 public class FileName {

 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 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);
 }
 }