-6

I am trying to find the file type in order to read the file based on its type. Input come in different file formats such as CVS, excel and orc etc..,

for example input =>"D:\\resources\\core_dataset.csv" I am expecting output => csv

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
Mojo
  • 13
  • 1
  • 2
  • 3
    Check out that [question](https://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java). It's in Java, but in Scala, you would do it very similarly. – Krzysztof Atłasik May 13 '19 at 09:35
  • 5
    Possible duplicate of [How do I get the file extension of a file in Java?](https://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java) – Prasad Khode May 13 '19 at 09:39

1 Answers1

2

You could achieve this as follows:

import java.nio.file.Paths

val path = "/home/gmc/exists.csv"
val fileName = Paths.get(path).getFileName            // Convert the path string to a Path object and get the "base name" from that path.
val extension = fileName.toString.split("\\.").last   // Split the "base name" on a . and take the last element - which is the extension.
// The above produces:

extension: String = csv
GMc
  • 1,764
  • 1
  • 8
  • 26
  • 2
    `val extension = fileName.toString.split("\\.").last` is makes a little less complex this solution – jseteny May 13 '19 at 16:33
  • @jseteny Of course. I am sure I tried using last but had an error which is why I went for the more complicated solution. I obviously tried it wrong. I'll update the answer and up vote your comment. – GMc May 13 '19 at 22:31
  • Hmmm, I'm not sure what you mean by "won't work withut extension"... If the input doesn't include an extension, it doesn't throw an exception, so IMHO it is still "working". If the base filename does not have a "dot" character, then this solution will simply return the base file name. Is that wrong or not what the OP expected? Maybe, but I don't know as I can't read the OP's mind and didn't want to over complicate the answer. The OP could always ask a follow up question if he/she were struggling with "no extension" file names, empty strings, null strings and any other potential variation. – GMc Jan 05 '21 at 03:51
  • See a point in both comments, but maybe you could a note about filenames without extension to the answer.  @GMc – Capuchin Aug 26 '21 at 07:45