使用String.substring()截取文件后缀需先用lastIndexOf(".")定位最后一个点,再判断其位置是否合法(>0且<length-1),最后调用substring(dotIndex+1)获取后缀;对无点、点在末尾等边界情况应返回空字符串。

<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 < str.length() - 1</code> 时,用 <strong>substring(dotIndex + 1)</strong> 得到后缀:</p>
<ul>
<li><code>"a/b/c.txt".substring("a/b/c.txt".lastIndexOf(".") + 1)</code> → <code>"txt"</code></li>
<li><code>"archive.tar.gz".substring("archive.tar.gz".lastIndexOf(".") + 1)</code> → <code>"gz"</code>(只取最后一段)</li>
<li>想取完整扩展名(如 <code>"tar.gz"</code>),需更复杂逻辑,<code>substring</code> 本身不支持多级后缀自动识别</li>
</ul>
<H3>简单安全的写法示例</H3>
<p>可封装成一行带保护的表达式:</p>
<font color="#666">String ext = fileName.lastIndexOf(".") > 0 && fileName.lastIndexOf(".") < fileName.length() - 1 ? fileName.substring(fileName.lastIndexOf(".") + 1) : "";</font>
<p>这样能避开无点、结尾为点等边界问题。</p>