使用系统文件分隔符分割文件名 [英] Splitting filenames using system file separator symbol
本文介绍了使用系统文件分隔符分割文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的指令:
String [] splittedFileName = fileName.split(System.getProperty(file.separator));
字符串simpleFileName = splittedFileName [splittedFileName.length-1];
但在Windows上,它提供了:
java.util.regex.PatternSyntaxException:在索引1附近发生意外的内部错误
$ / code $
我可以避免这个异常吗?有没有更好的方法来做到这一点? $ c>必须被转义才能在正则表达式中使用作为反斜杠。您应该使用分割API 不使用正则表达式,或者使用 .html#quote%28java.lang.String%29> Pattern.quote
第一:
//可选:使用Pattern.quote(File.separator)
String pattern = Pattern.quote(System.getProperty(file.separator));
String [] splittedFileName = fileName.split(pattern);
甚至更好,使用 File
API为此:
文件file = new File(fileName);
字符串simpleFileName = file.getName();
I have a complete file path and I want to get the file name.
I am using the following instruction:
String[] splittedFileName = fileName.split(System.getProperty("file.separator"));
String simpleFileName = splittedFileName[splittedFileName.length-1];
But on Windows it gives:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Can I avoid this exception? Is there a better way to do this?
解决方案
The problem is that \
has to be escaped in order to use it as backslash within a regular expression. You should either use a splitting API which doesn't use regular expressions, or use Pattern.quote
first:
// Alternative: use Pattern.quote(File.separator)
String pattern = Pattern.quote(System.getProperty("file.separator"));
String[] splittedFileName = fileName.split(pattern);
Or even better, use the File
API for this:
File file = new File(fileName);
String simpleFileName = file.getName();
这篇关于使用系统文件分隔符分割文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文