Remove filename extension in Java

后端 未结 10 2265
你的背包
你的背包 2020-12-09 08:48

(Without including any external libraries.)

What\'s the most efficient way to remove the extension of a filename in Java, without assuming anything of the f

10条回答
  •  情书的邮戳
    2020-12-09 09:20

    It's actually very easy, assuming that you have a valid filename.

    In Windows filenames the dot character is only used to designate an extension. So strip off the dot and anything after it.

    In unix-like filenames the dot indicates an extension if it's after the last separator ('/') and has at least one character between it and the last separator (and is not the first character, if there are no separators). Find the last dot, see if it satisfies the conditions, and strip it and any trailing characters if it does.

    It's important that you validate the filename before you do this, as this algorithm on an invlaid filename might do something unexpected and generate a valid filename. So in Windows you may need to check that there isn't a backslash, or a colon, after the dot.

    If you don't know what kind of filename you are dealing with, treating them all like Unix will get you most of the way.

提交回复
热议问题