0

我有一个查询方法,其中参数作为文件名出现,在调试时我已经分析过,如下所示:

private processfile ( string filePath)

{

}

现在这个文件路径可以是:

C:\abc\file1.txt
or 
C:\abc\def\file1.txt
or 
C:\ghj\ytr\wer\file1.txt

现在我的查询是我必须只提取文件名并且必须存储在字符串参数中。所以我必须将 存储file1.txt在一个字符串中,比如说在一个字符串参数s中,所以最终s将存储为

String s = file1.txt

如何做到这一点?

4

2 回答 2

10

这应该可以解决问题

String s = new File(filepath).getName()

虽然我会将文件路径重命名为 filePath。

你可以在这里File#getName()找到文档

于 2013-05-16T09:02:28.513 回答
3

对于这种情况,您可以使用indexOfand :substring

String s = filepath.substring(filepath.lastIndexOf(File.separator)+1);

File.getName也采取类似的方法,见下面的来源:

public String getName() {
    int index = path.lastIndexOf(separatorChar);
    if (index < prefixLength) return path.substring(prefixLength);
    return path.substring(index + 1);
    }
于 2013-05-16T09:03:01.137 回答