Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Java get Filename without Extension

Related Tutorials


 
 

Share on Google+Share on Google+

Java get Filename without Extension

Advertisement
In this section, you will learn how to obtain the filename without extension. For this, the file name or the directory name is being provided.

Java get Filename without Extension

     

In this section, you will learn how to obtain the filename without extension. For this, the file name or the directory name is being provided.

file.getName()- This method returns the file name.

lastIndexOf()-This method returns the index within this string.

file.length()-This method returns the length of the file.

substring(0, index)-  This method returns a new string that is a substring of this string.

Here is the code of GetFilenameWithoutExtension.java

import java.io.File;
public class GetFilenameWithoutExtension{

public static String getFileNameWithoutExtension() {
  String fileName="C:\\anu\\My\\Hello.txt";
  File file = new File(fileName);
  
  int index = file.getName().lastIndexOf('.');
      if (index>0&& index <= file.getName().length() - 2 ) {
      System.out.println("Filename without Extension: "+file.getName().substring(0, index));
      }  
    return "";
    }
public static void main(String []args){
GetFilenameWithoutExtension example=new GetFilenameWithoutExtension();
example.getFileNameWithoutExtension();
}
}

Output will be displayed as:

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: November 1, 2008

Related Tutorials

Discuss: Java get Filename without Extension  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
raj
October 3, 2012
Doesn't work for me.

Getting the file with extension.
DMCA.com