使用string.substring()截取文件后缀需先用lastindexof(".")定位最后一个点,再判断其位置是否合法(>0且

<p>直接用 <strong>String.substring()</strong> 截取文件后缀名,关键在于准确定位最后一个点(<code>.</code>)的位置。后缀名是最后一个点之后的部分,不包含点本身。</p>
<h3>找到最后一个点的索引</h3>
<p>使用 <strong>lastIndexOf(".")</strong> 获取最后一个点在字符串中的位置。注意:如果文件名没有点(如 <code>README</code>)或以点开头(如 <code>.gitignore</code>),需额外判断,避免返回 -1 或截取出错。</p>
<h3>检查是否有效存在后缀</h3>
<p>若 <code>lastIndexOf(".") == -1</code>,说明无点,也就没有标准后缀;若点在末尾(如 <code>name.</code>),则后缀为空;通常还应排除点在路径分隔符之后、但位于目录名中的情况(如 <code>/path.to/file.txt</code> 中的 <code>path.to</code> 是目录名,不是后缀)。不过对纯文件名字符串,只需关注最后一个点即可。</p>
<h3>调用 substring 截取</h3>
<p>当确认最后一个点位置为 <code>dotIndex</code> 且 <code>dotIndex > 0</code> 且 <code>dotIndex 时,用 <strong>substring(dotIndex + 1)</strong> 得到后缀:</code></p>
-
"a/b/c.txt".substring("a/b/c.txt".lastIndexOf(".") + 1)→"txt" -
"archive.tar.gz".substring("archive.tar.gz".lastIndexOf(".") + 1)→"gz"(只取最后一段) - 想取完整扩展名(如
"tar.gz"),需更复杂逻辑,substring本身不支持多级后缀自动识别
简单安全的写法示例
可封装成一行带保护的表达式:
String ext = fileName.lastIndexOf(".") > 0 && fileName.lastIndexOf(".")这样能避开无点、结尾为点等边界问题。










