I recently started working on grails and i want to know how to get the extension of a file. Ex: test.txt. I want to check extension(txt)? any clue?
Asked
Active
Viewed 2,865 times
3

DirtyMind
- 2,353
- 2
- 22
- 43
-
1See http://stackoverflow.com/questions/5019478/grails-file-upload-how-to-recognize-file-and-or-content-type – Mihai8 Oct 02 '15 at 22:41
-
Please dont mind. What exactly the contentType will return ? is it same as mediaType. Like mediaType will return text/plain for .txt file and the same will return for xml json. – DirtyMind Oct 02 '15 at 22:46
-
Possible duplicate of [How do I get the file extension of a file in Java?](http://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java) – cfrick Oct 03 '15 at 09:34
3 Answers
4
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}

Emmanuel Rosa
- 9,697
- 2
- 14
- 20
-
-
Yes. The regex boils down to: everything after the last period. So it can handle file extensions of arbitrary length. Just add them to the list. – Emmanuel Rosa Oct 03 '15 at 01:43
1
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~
to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)

smac89
- 39,374
- 15
- 132
- 179
0
Hope i found the answer of my Question. How to find the extension of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}