Pin It

How to determine whether a file name ends with a given string in Java ?.

Program to demonstrate how to determine whether a file name ends with a given string in Java

package com.hubberspot.code;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileType {

 public static void main(String[] args) {

  try {
   // Creating a file with a name files.txt
   // placed in the root folder of your Java 
   // project in eclipse
   // Storing the name of file as a String
   String fileName = "files.txt";

   // Creating a File object by passing it a 
   // String containing the name of file
   File file = new File(fileName);

   // Creating a Scanner object using a constructor
   // which takes the file object. There are various 
   // constructors for Scanner class for different
   // purposes. We want to use Scanner class to read
   // data from a file on the system, So we are using 
   // a constructor which is taking an File object
   Scanner scanner = new Scanner(file);

   // Scanner class has many methods for scanning file
   // line-by-line. We use hasNextLine method which returns
   // true if there is yet another line to be read. putting the
   // condition in the while loop we traverse file line by line
   // and as soon as new line is figured out, we capture it by 
   // Scanner class's nextLine method and prints it on the console
   while(scanner.hasNextLine()) {
    String files = scanner.nextLine();

    System.out.print(files +" is a ");

    // findFileType() takes in a string which is 
    // name of the file read from the files.txt
    findFileType(files);

   }
  }
  catch (FileNotFoundException e) {

   e.printStackTrace();
  }

 }

 // This method uses String class endsWith() method
 // taking in the string by which file name ends.
 // It uses this string to search for a substring 
 // in the name of file that whether its of particular
 // type or not
 public static void findFileType(String fileName) {

  if(fileName.endsWith(".txt")){
   System.out.println("Text file");
  } 
  else if (fileName.endsWith(".doc")){
   System.out.println("Document file");
  }
  else if (fileName.endsWith(".ppt")){
   System.out.println("Presentation file");
  }
  else if (fileName.endsWith(".xls")){
   System.out.println("Excel file");
  } 
  else if (fileName.endsWith(".java")){
   System.out.println("Java source file");
  } 
  else {
   System.out.println("Other type of file");
  }
 }
}






a) files.txt :-

 










b) Output of the program :

Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot