【问题标题】:Given the file path find the file extension using Scala?给定文件路径,使用 Scala 找到文件扩展名?
【发布时间】:2019-09-30 05:30:35
【问题描述】:

我正在尝试查找文件类型,以便根据文件类型读取文件。 输入有不同的文件格式,如 CVS、excel 和 orc 等,

例如输入 =>"D:\\resources\\core_dataset.csv" 我期待输出 => csv

【问题讨论】:

标签: scala apache-spark apache-spark-sql scala-collections


【解决方案1】:

您可以通过以下方式实现:

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

【讨论】:

  • val extension = fileName.toString.split("\\.").last 使这个解决方案变得不那么复杂
  • @jseteny 当然。我确定我尝试使用 last 但有一个错误,这就是我选择更复杂的解决方案的原因。我显然试错了。我会更新答案并对您的评论进行投票。
  • 嗯,我不确定您所说的“没有扩展名将无法工作”是什么意思......如果输入不包含扩展名,它不会引发异常,所以恕我直言它仍在“工作”。如果基本文件名没有“点”字符,则此解决方案将简单地返回基本文件名。这是错误的还是不是OP所期望的?也许吧,但我不知道,因为我无法读懂 OP 的想法,也不想让答案过于复杂。如果 OP 一直在为“无扩展名”文件名、空字符串、空字符串和任何其他潜在变化而苦苦挣扎,他/她总是可以提出后续问题。
  • 在两个 cmets 中都看到了一点,但也许您可以在没有答案扩展名的情况下记录文件名。 @GMc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多