字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
当前回答
使用Java regex *提取文件名。
public String extractFileName(String fullPathFile){
try {
Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
Matcher regexMatcher = regex.matcher(fullPathFile);
if (regexMatcher.find()){
return regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
}
return fullPathFile;
}
其他回答
只需使用File.getName()
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());
使用String方法:
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));
您可以使用FileInfo对象来获取文件的所有信息。
FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
MessageBox.Show(f.Name);
MessageBox.Show(f.FullName);
MessageBox.Show(f.Extension );
MessageBox.Show(f.DirectoryName);
使用Java regex *提取文件名。
public String extractFileName(String fullPathFile){
try {
Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
Matcher regexMatcher = regex.matcher(fullPathFile);
if (regexMatcher.find()){
return regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
}
return fullPathFile;
}
自1.7年
Path p = Paths.get("c:\\temp\\1.txt");
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();
考虑到你问的那个字符串
C:\Hello\AnotherFolder\The File Name.PDF
我们需要提取最后一个分隔符之后的所有内容。\。这正是我们感兴趣的。
你可以这样做
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
这将检索字符串中最后一个\的索引,并将它之后的所有内容提取到fileName中。
如果String中有不同的分隔符,请调整lastIndexOf以使用该分隔符。(甚至有一个重载接受整个String作为分隔符。)
我在上面的例子中省略了它,但是如果您不确定String来自哪里或者它可能包含什么内容,您将希望验证lastIndexOf返回一个非负值,因为Javadoc声明它将返回
-1,如果没有发生