how to get the file extension from a pathname

J

jimgardener

hi
i want to extract the extension of a file as a String.Suppose the
pathname of file is F:\mycode\myimage\newimg.jpg
i need to get the extension 'jpg' only
I did it like this,

public static void main(String [] args){
String imagetomatch=args[0];
String[] words=imagetomatch.split(java.io.File.pathSeparator);
String ext=(words[words.length-1].split("\\.")[1]);
System.out.println("ext="+ext);
}

is there a better/compact way to do this?

Also ,why does'nt the .split(".") work in the above case.Why do i have
to use .split("\\.")?
thanks
jim
 
J

John B. Matthews

jimgardener said:
hi
want to extract the extension of a file as a String.Suppose the
pathname of file is F:\mycode\myimage\newimg.jpg need to get the
extension 'jpg' only. I did it like this,

public static void main(String [] args){
String imagetomatch=args[0];
String[] words=imagetomatch.split(java.io.File.pathSeparator);
String ext=(words[words.length-1].split("\\.")[1]);
System.out.println("ext="+ext);
}

is there a better/compact way to do this?


You might look at java.io.File#getName()

Also, why does'nt the .split(".") work in the above case.Why do
have to use .split("\\.")?


The symbol '.' represents one of the predefined character classes (any
character) in a java.util.regex.Pattern:

<http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html>

In contrast, you're looking for the literal character '\u002E'
(full-stop, period, dot, decimal, etc.) A regex parameter containing a
single backslash ("\.") would be seen as an illegal escape character:

<http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#25687
Using two backslashes signals that the second one is a literal '\'
character to be sent to the regex parser, which then uses it to escape
the special meaning of '.'.

[It's like a day at the beach, littorally.]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top