如何从包含绝对文件路径的字符串中获取文件名?

时间:2021-03-02 16:01:32

String variable contains a file name, C:\Hello\AnotherFolder\The File Name.PDF. How do I only get the file name The File Name.PDF as a String?

字符串变量包含一个文件名,C:\你好\另一个文件夹\文件名称。pdf。如何只获取文件名文件名文件名。PDF作为字符串?

I planned to split the string, but that is not the optimal solution.

我计划拆分字符串,但这不是最优解。

10 个解决方案

#1


175  

just use File.getName()

只使用File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

使用字符串方法:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));

#2


198  

Alternative using Path (Java 7+):

选择使用路径(Java 7+):

Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

Note that splitting the string on \\ is platform dependent as the file separator might vary. Path#getName takes care of that issue for you.

注意,在\\ \\ \\ \中拆分字符串取决于平台,因为文件分隔符可能不同。路径#getName为您处理这个问题。

#3


29  

Considering the String you're asking about is

考虑到你问的弦

C:\Hello\AnotherFolder\The File Name.PDF

we need to extract everything after the last separator, ie. \. That is what we are interested in.

我们需要在最后一个分隔符之后提取所有东西。\。这就是我们感兴趣的。

You can do

你可以做

String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);

This will retrieve the index of the last \ in your String and extract everything that comes after it into fileName.

这将检索您的字符串中最后一个\的索引,并将后面的所有内容提取到fileName中。

If you have a String with a different separator, adjust the lastIndexOf to use that separator. (There's even an overload that accepts an entire String as a separator.)

如果您有一个带有不同分隔符的字符串,请调整lastIndexOf以使用该分隔符。(甚至有一个重载接受整个字符串作为分隔符。)

I've omitted it in the example above, but if you're unsure where the String comes from or what it might contain, you'll want to validate that the lastIndexOf returns a non-negative value because the Javadoc states it'll return

在上面的示例中我省略了它,但是如果您不确定这个字符串来自哪里,或者它可能包含什么,您将希望验证lastIndexOf返回一个非负值,因为Javadoc声明它将返回

-1 if there is no such occurrence

-如果没有这种情况

#4


23  

Using FilenameUtils in Apache Commons IO :

在Apache Commons IO中使用fil珐琅词:

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

#5


15  

Since 1.7

自1.7年

    Path p = Paths.get("c:\\temp\\1.txt");
    String fileName = p.getFileName().toString();
    String directory = p.getParent().toString();

#6


12  

you can use path = C:\Hello\AnotherFolder\TheFileName.PDF

你可以使用path = C:\Hello\其他文件夹\TheFileName.PDF

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());

#7


7  

The other answers didn't quite work for my specific scenario, where I am reading paths that have originated from an OS different to my current one. To elaborate I am saving email attachments saved from a Windows platform on a Linux server. The filename returned from the JavaMail API is something like 'C:\temp\hello.xls'

其他答案对我的特定场景并不适用,我正在读取源自与当前操作系统不同的操作系统的路径。为了详细说明,我正在保存从Linux服务器上的Windows平台中保存的电子邮件附件。从JavaMail API返回的文件名类似于'C:\temp\hello.xls'

The solution I ended up with:

我的解决方案是:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

#8


2  

A method without any dependency and takes care of .. , . and duplicate separators.

一种没有任何依赖关系的方法。,。和重复的分隔符。

public static String getFileName(String filePath) {
    if( filePath==null || filePath.length()==0 )
        return "";
    filePath = filePath.replaceAll("[/\\\\]+", "/");
    int len = filePath.length(),
        upCount = 0;
    while( len>0 ) {
        //remove trailing separator
        if( filePath.charAt(len-1)=='/' ) {
            len--;
            if( len==0 )
                return "";
        }
        int lastInd = filePath.lastIndexOf('/', len-1);
        String fileName = filePath.substring(lastInd+1, len);
        if( fileName.equals(".") ) {
            len--;
        }
        else if( fileName.equals("..") ) {
            len -= 2;
            upCount++;
        }
        else {
            if( upCount==0 )
                return fileName;
            upCount--;
            len -= fileName.length();
        }
    }
    return "";
}

Test case:

测试用例:

@Test
public void testGetFileName() {
    assertEquals("", getFileName("/"));
    assertEquals("", getFileName("////"));
    assertEquals("", getFileName("//C//.//../"));
    assertEquals("", getFileName("C//.//../"));
    assertEquals("C", getFileName("C"));
    assertEquals("C", getFileName("/C"));
    assertEquals("C", getFileName("/C/"));
    assertEquals("C", getFileName("//C//"));
    assertEquals("C", getFileName("/A/B/C/"));
    assertEquals("C", getFileName("/A/B/C"));
    assertEquals("C", getFileName("/C/./B/../"));
    assertEquals("C", getFileName("//C//./B//..///"));
    assertEquals("user", getFileName("/user/java/.."));
    assertEquals("C:", getFileName("C:"));
    assertEquals("C:", getFileName("/C:"));
    assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
    assertEquals("C.ext", getFileName("/A/B/C.ext"));
    assertEquals("C.ext", getFileName("C.ext"));
}

Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.

可能getFileName有点混乱,因为它也返回目录名。它返回路径中文件或最后一个目录的名称。

#9


0  

extract file name using java regex *.

使用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;
    }

#10


0  

Considere the case that Java is Multiplatform:

考虑到Java是多平台的情况:

int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
    fileName = fileName.substring(lastPath+1);
}

#1


175  

just use File.getName()

只使用File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

使用字符串方法:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));

#2


198  

Alternative using Path (Java 7+):

选择使用路径(Java 7+):

Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

Note that splitting the string on \\ is platform dependent as the file separator might vary. Path#getName takes care of that issue for you.

注意,在\\ \\ \\ \中拆分字符串取决于平台,因为文件分隔符可能不同。路径#getName为您处理这个问题。

#3


29  

Considering the String you're asking about is

考虑到你问的弦

C:\Hello\AnotherFolder\The File Name.PDF

we need to extract everything after the last separator, ie. \. That is what we are interested in.

我们需要在最后一个分隔符之后提取所有东西。\。这就是我们感兴趣的。

You can do

你可以做

String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);

This will retrieve the index of the last \ in your String and extract everything that comes after it into fileName.

这将检索您的字符串中最后一个\的索引,并将后面的所有内容提取到fileName中。

If you have a String with a different separator, adjust the lastIndexOf to use that separator. (There's even an overload that accepts an entire String as a separator.)

如果您有一个带有不同分隔符的字符串,请调整lastIndexOf以使用该分隔符。(甚至有一个重载接受整个字符串作为分隔符。)

I've omitted it in the example above, but if you're unsure where the String comes from or what it might contain, you'll want to validate that the lastIndexOf returns a non-negative value because the Javadoc states it'll return

在上面的示例中我省略了它,但是如果您不确定这个字符串来自哪里,或者它可能包含什么,您将希望验证lastIndexOf返回一个非负值,因为Javadoc声明它将返回

-1 if there is no such occurrence

-如果没有这种情况

#4


23  

Using FilenameUtils in Apache Commons IO :

在Apache Commons IO中使用fil珐琅词:

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

#5


15  

Since 1.7

自1.7年

    Path p = Paths.get("c:\\temp\\1.txt");
    String fileName = p.getFileName().toString();
    String directory = p.getParent().toString();

#6


12  

you can use path = C:\Hello\AnotherFolder\TheFileName.PDF

你可以使用path = C:\Hello\其他文件夹\TheFileName.PDF

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());

#7


7  

The other answers didn't quite work for my specific scenario, where I am reading paths that have originated from an OS different to my current one. To elaborate I am saving email attachments saved from a Windows platform on a Linux server. The filename returned from the JavaMail API is something like 'C:\temp\hello.xls'

其他答案对我的特定场景并不适用,我正在读取源自与当前操作系统不同的操作系统的路径。为了详细说明,我正在保存从Linux服务器上的Windows平台中保存的电子邮件附件。从JavaMail API返回的文件名类似于'C:\temp\hello.xls'

The solution I ended up with:

我的解决方案是:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

#8


2  

A method without any dependency and takes care of .. , . and duplicate separators.

一种没有任何依赖关系的方法。,。和重复的分隔符。

public static String getFileName(String filePath) {
    if( filePath==null || filePath.length()==0 )
        return "";
    filePath = filePath.replaceAll("[/\\\\]+", "/");
    int len = filePath.length(),
        upCount = 0;
    while( len>0 ) {
        //remove trailing separator
        if( filePath.charAt(len-1)=='/' ) {
            len--;
            if( len==0 )
                return "";
        }
        int lastInd = filePath.lastIndexOf('/', len-1);
        String fileName = filePath.substring(lastInd+1, len);
        if( fileName.equals(".") ) {
            len--;
        }
        else if( fileName.equals("..") ) {
            len -= 2;
            upCount++;
        }
        else {
            if( upCount==0 )
                return fileName;
            upCount--;
            len -= fileName.length();
        }
    }
    return "";
}

Test case:

测试用例:

@Test
public void testGetFileName() {
    assertEquals("", getFileName("/"));
    assertEquals("", getFileName("////"));
    assertEquals("", getFileName("//C//.//../"));
    assertEquals("", getFileName("C//.//../"));
    assertEquals("C", getFileName("C"));
    assertEquals("C", getFileName("/C"));
    assertEquals("C", getFileName("/C/"));
    assertEquals("C", getFileName("//C//"));
    assertEquals("C", getFileName("/A/B/C/"));
    assertEquals("C", getFileName("/A/B/C"));
    assertEquals("C", getFileName("/C/./B/../"));
    assertEquals("C", getFileName("//C//./B//..///"));
    assertEquals("user", getFileName("/user/java/.."));
    assertEquals("C:", getFileName("C:"));
    assertEquals("C:", getFileName("/C:"));
    assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
    assertEquals("C.ext", getFileName("/A/B/C.ext"));
    assertEquals("C.ext", getFileName("C.ext"));
}

Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.

可能getFileName有点混乱,因为它也返回目录名。它返回路径中文件或最后一个目录的名称。

#9


0  

extract file name using java regex *.

使用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;
    }

#10


0  

Considere the case that Java is Multiplatform:

考虑到Java是多平台的情况:

int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
    fileName = fileName.substring(lastPath+1);
}