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

发布于 2025-02-03 04:03:33 字数 151 浏览 4 评论 0原文

字符串变量包含一个文件名,c:\ Hello \ elesherfolder \ file name.pdf。我如何将文件名作为字符串获取文件名

我计划将字符串分开,但这不是最佳解决方案。

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

忆伤 2025-02-10 04:03:33

只需使用 file。 getName()

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

使用字符串方法

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

just use 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));
红玫瑰 2025-02-10 04:03:33

使用 path (java 7+):

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

请注意,\\将字符串分配为平台依赖性,因为文件分离器可能会有所不同。 路径#getName为您解决这个问题。

Alternative using Path (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.

灰色世界里的红玫瑰 2025-02-10 04:03:33

使用filenameutils in apache commons io

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

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
错々过的事 2025-02-10 04:03:33

任何文件名/路径操作都应在 java.nio.file package

具体来说, <代码>路径 class

[...]可用于在文件系统中找到文件。它通常代表系统依赖的文件路径。

A路径代表层次结构的路径,由由特殊分离器或定界符分隔的目录和文件名元素组成。也可能存在标识文件系统层次结构的根组件。 距目录层次结构根最远的名称元素是文件或目录的名称。 [...]

您可以使用 paths工厂方法,get (或所述filesystems类,如上所述在这里)。

一旦拥有适当的路径>代表完整路径的实例,您就可以使用 getfilename

返回该路径表示为路径对象的文件或目录的名称。文件名是目录层次结构中的root 的最远元素。


例如,

String fullPathStr = "C:\Hello\AnotherFolder\The File Name.PDF";
Path fullPath = Paths.get(fullPathStr);
Path fileName = fullPath.getFileName();

注意:所有这些都假定您在Windows环境中运行(考虑您的文件路径)。如果没有,您需要使用 filesystemprovider 支持Windows路径命名。


另外,只有字符串操作,并且考虑字符串您要问的是

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);

那 /代码>。

如果您有一个带有不同分离器的字符串,请调整lastIndexof使用该分隔符。(甚至还有 Overload 接受整个<代码>字符串作为分隔符。)

我在上面的示例中省略了它,但是如果您不确定String来自何处或可能包含的位置,您将需要要验证lastIndexof返回非负值,因为 javadoc states 它将返回

-1如果没有这种情况

Any file name/path manipulation should go through APIs in the java.nio.file package.

Specifically, the Path class

[...] may be used to locate a file in a file system. It will typically represent a system dependent file path.

A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. [...]

You can get an instance of type Path using the Paths factory method, get (or the FileSystems class as described here).

Once you have an appropriate Path instance representing your full path, you can use getFileName

Returns the name of the file or directory denoted by this path as a Path object. The file name is the farthest element from the root in the directory hierarchy.

For example,

String fullPathStr = "C:\Hello\AnotherFolder\The File Name.PDF";
Path fullPath = Paths.get(fullPathStr);
Path fileName = fullPath.getFileName();

Note: This all assumes you're running in a Windows environment (considering your file path). If not, you'll need to use a FileSystemProvider that supports Windows path naming.


Alternatively, with only string manipulation, and 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.

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.)

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

-1 if there is no such occurrence

烟若柳尘 2025-02-10 04:03:33

自1.7以来

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

Since 1.7

    Path p = Paths.get("c:\\temp\\1.txt");
    String fileName = p.getFileName().toString();
    String directory = p.getParent().toString();
猫九 2025-02-10 04:03:33

其他答案对我的特定情况并不完全有用,在该方案中,我正在阅读与当前的操作系统不同的源自操作系统的路径。为了详细说明,我要保存从Linux服务器上的Windows平台保存的电子邮件附件。从Javamail API返回的文件名类似于“ C:\ temp \ Hello.xls”

我最终得到的解决方案:

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

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'

The solution I ended up with:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];
拥有 2025-02-10 04:03:33

您可以使用路径= c:\ hello \ enosefolder \ thefilename.pdf

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

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

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());
灰色世界里的红玫瑰 2025-02-10 04:03:33

java.nio.file.path的getFilename()方法用于返回该路径对象指向的文件或目录的名称。

路径getFilename()

参考的

https:https:https:// wwww。 geeksforgeeks.org/path-getfilename-method-in-java-with-examples/

getFileName() method of java.nio.file.Path used to return the name of the file or directory pointed by this path object.

Path getFileName()

For reference:

https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/

澜川若宁 2025-02-10 04:03:33

认为Java是乘数:

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

Considere the case that Java is Multiplatform:

int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
    fileName = fileName.substring(lastPath+1);
}
笑忘罢 2025-02-10 04:03:33

一种无依赖性的方法,并照顾 .. 和重复的分离器。

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
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"));
}

也许GetFilename有点令人困惑,因为它也返回目录名称。它在路径中返回文件的名称或最后一个目录。

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.

Spring初心 2025-02-10 04:03:33

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

extract file name using 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;
    }
无敌元气妹 2025-02-10 04:03:33

您可以使用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);

You can use FileInfo object to get all information of your file.

    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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文