我基本上是在尝试在最后一个句点上拆分字符串以捕获文件扩展名。但有时文件没有任何扩展名,所以我期待这一点。
但问题是有些文件名在结尾前有句点,就像这样......
/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 - 连接(壮举)"。
这就是我一直在使用的东西...
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);
如何在文件扩展名处拆分字符串,但也能够在文件没有扩展名时进行处理和警报。
试试这个
int i = s.lastIndexOf(c);
String[] a = {s.substring(0, i), s.substring(i)};
假设以点后跟字母数字字符结尾的文件具有扩展名可能更容易。
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 文档。请记住转义反斜杠,因为模式字符串需要反斜杠。
这是Java吗?如果是这样,为什么不使用"java.io.File.getName"。
例如:
File f = new File("/aaa/bbb/ccc.txt");
System.out.println(f.getName());
外:
ccc.txt
您可以在正则表达式中使用积极的前瞻,以确保它仅在最后一次出现时拆分。 积极的前瞻可确保它仅在字符串后面看不到其他匹配项时才拆分。
// Using example filePath from question
String filePath = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
String[] parts = filePath.split("\.(?=[^.]*$)");
// parts = [
// "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped)"
// "mp3"
// ]
分解正则表达式:
-
\.
- 查找经期 -
(?=[^.]*$)
- 确保之后的所有内容都不是句号,不要将其包含在比赛中)
你可以从apache commons使用StringUtils,这是一种提取文件类型的优雅方式。
String example = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
String format = StringUtils.substringAfterLast(example, ".");
System.out.println(format);
程序将在控制台中打印"mp3"。
如何使用句点作为分隔符来拆分 filPath。并获取该数组中的最后一项来获取扩展名:
String fileTypeArray[] = filePath.split(",");
String fileType = "";
if(fileTypeArray != null && fileTypeArray.length > 0) {
fileType = fileTypeArray[fileTypeArray.length - 1];
}
对于任意长度的任意拆分字符串c
:
int i = s.lastIndexOf(c);
String[] a = {s.substring(0, i), s.substring(i+c.length())};