在某个字符的最后一次出现时拆分字符串

2022-09-01 02:18:33

我基本上试图在最后一个句点拆分一个字符串以捕获文件扩展名。但有时文件没有任何扩展名,所以我期待这一点。

但问题是,有些文件名在结尾之前有句点,就像这样......

/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3

因此,当那根绳子出现时,它会在“02 Drake - Connect(Feat)”处将其切碎。

这就是我一直在使用的东西...

String filePath = intent.getStringExtra(ARG_FILE_PATH);
String fileType = filePath.substring(filePath.length() - 4);
String FileExt = null;
try {
    StringTokenizer tokens = new StringTokenizer(filePath, ".");
    String first = tokens.nextToken();
    FileExt = tokens.nextToken();
}
catch(NoSuchElementException e) {
    customToast("the scene you chose, has no extension :(");
}
System.out.println("EXT " + FileExt);
File fileToUpload = new File(filePath);

我如何在文件扩展名处拆分字符串,但也能够在文件没有扩展名时处理和发出警报。


答案 1

你可以试试这个

int i = s.lastIndexOf(c);
String[] a =  {s.substring(0, i), s.substring(i)};

答案 2

假设以点后跟字母数字字符结尾的文件具有扩展名可能会更容易。

int p=filePath.lastIndexOf(".");
String e=filePath.substring(p+1);
if( p==-1 || !e.matches("\\w+") ){/* file has no extension */}
else{ /* file has extension e */ }

有关正则表达式模式,请参阅 Java 文档。请记住转义反斜杠,因为模式字符串需要反斜杠。