Home Java Java-get-example Java example program to get extension

Related Tutorials


 
 

Share on Google+Share on Google+

Java example program to get extension

Advertisement
To get the file name and file extension separately we can do the string manipulation on the file name. Suppose "filename.ext" is some filename with extension is provided.

Java example program to get extension

     

java get extension

To get the file name and file extension separately we can do the string manipulation on the file name. Suppose "filename.ext" is some filename with extension is provided. To get the filename and extension we will be calculating the last index of "." and will split the file name from this ".", since characters after this "." represents the extension of the file. GetFileExtension.java is as follows:

 

GetFileExtension.java

import java.util.*;
import java.lang.*;

public class GetFileExtension
{
  public static void main(String args[]) {
  String fileName = args[0];
  String fname="";
  String ext="";
  int mid= fileName.lastIndexOf(".");
  fname=fileName.substring(0,mid);
  ext=fileName.substring(mid+1,fileName.length());  
  System.out.println("File name ="+fname);
  System.out.println("Extension ="+ext);  
  }
}

Output:

C:\javaexamples>javac GetFileExtension.java

C:\javaexamples>java GetFileExtension document.doc
File name =document
Extension =doc

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2008

Related Tutorials

Discuss: Java example program to get extension   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
sachin sharma
September 1, 2011
get the idea for my project based on java.

i want know more about, how java find that any given file is a image or video or web document file!!!
minlser
June 13, 2012
runtime exception from without extention file

Thanks for sample. but might throw IndexOutOfBoundsException in fname=fileName.substring(0,mid); if file have not extension.
Rajendra
April 5, 2013
about java

sir . iam new about java. please reply me 1-where do we write java coading and where save it? 2-as like .html,.doc,are the extention name so what is java extentiopn name? 3-where we will Run java ?
DMCA.com