How to extract file extension from string scala

Viewed 480

I am Trying to extract file extension from file path using below method.

import java.nio.file.Paths
val filename_path = "s3://bucket-name/filepath/file.csv" 

// Convert the path string to a Path object and get the "base name" from that path.

val fileName = Paths.get(filename_path).getFileName

val extension = fileName.toString.split("\\.").last 

Above codes work fines for path which does not have any compression in file extension. if i pass file path as

case 1 : val filename_path_1 = "s3://bucket-name/filepath/file.csv.gz" 
case 2 : val filename_path_2 = "s3://bucket-name/filepath/file.csv" 
case 3 : val filename_path_2 = "s3://bucket-name/filepath/file.parquet"
case 4 : val filename_path_2 = "s3://bucket-name/filepath/file.parquet.gz"
case 5 : val filename_path_2 = "s3://bucket-name/filepath/gz.parquet"

in above case i would like to obtain output as below:

case 1 -> csv
case 2 -> csv
case 3 -> parquet
case 4 -> parquet
case 5 -> parquet

Regards mahi

1 Answers

You could try this approach

def getExtension(extension: String): String = {
    match extension {
        case(csv) if csv.contains("csv") => "csv"
        case(parquet) if parquet.contains("parquet") => "parquet"
        ....
        case(validExt) if validExt.contains("validExt") => "validExt"
        case _ => // rest of the cases that you can code as ".tmp or .xml or ...."
    }
}
Related