Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using String.endswith() method on Java

Tags:

java

I have an array I want to check the the last digits if it is in the array.

Example:

String[] types = {".png",".jpg",".gif"}

String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types); 

Please note: I know I can check each individual item using a for loop.

I want to know if there is a more efficient way of doing this. Reason being is that image string is already on a loop on a constant change.

like image 396
Gearsdf Gearsdfas Avatar asked Jun 19 '12 18:06

Gearsdf Gearsdfas


2 Answers

Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
like image 65
Nathan Hughes Avatar answered Sep 24 '22 02:09

Nathan Hughes


You can substring the last 4 characters:

String ext = image.substring(image.length - 4, image.length);

and then use a HashMap or some other search implementation to see if it is in your list of approved file extensions.

if(fileExtensionMap.containsKey(ext)) {

like image 31
David B Avatar answered Sep 23 '22 02:09

David B