如何在Java中不带扩展名的文件名?

谁能告诉我如何获取不带扩展名的文件名?例:


fileNameWithExt = "test.xml";

fileNameWithOutExt = "test";


月关宝盒
浏览 1786回答 3
3回答

呼啦一阵风

如果像我一样,如果您希望在某些可能考虑了所有特殊情况的地方使用一些库代码,例如,如果在路径中输入null或点而不在文件名中输入时会发生什么,则可以使用以下代码:import org.apache.commons.io.FilenameUtils;String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);

郎朗坤

请参阅以下测试程序:public class javatemp {    static String stripExtension (String str) {        // Handle null case specially.        if (str == null) return null;        // Get position of last '.'.        int pos = str.lastIndexOf(".");        // If there wasn't any '.' just return the string as is.        if (pos == -1) return str;        // Otherwise return the string, up to the dot.        return str.substring(0, pos);    }    public static void main(String[] args) {        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));        System.out.println ("test       -> " + stripExtension ("test"));        System.out.println ("test.      -> " + stripExtension ("test."));    }}输出:test.xml   -> testtest.2.xml -> test.2test       -> testtest.      -> test
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java