4

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

0

1 Answer 1

1

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 ...."
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Chema, this is would work fine but then i need to hard code match cases for all as of now i am have only few cases which i can hard code for rest other i want extension to be as is like .xml to be a .xml which will be going in validExt can we do that if none of the above then match the case and return for all
validExt could be any valid extension(.txt,.json......), _ => for the rest of the cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.