从Java中的文件位置获取文件名 [英] Get file name from a file location in Java

查看:160
本文介绍了从Java中的文件位置获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 String ,它提供了一个文件的绝对路径(包括文件名)。我想得到文件的名称。最简单的方法是什么?

I have a String that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this?

它需要尽可能通用,因为我事先无法知道URL是什么。我不能简单地创建一个URL对象并使用 getFile() - 所有这些都是理想的,如果可能的话 - 因为它不一定是 http:// 前缀可以是c:/或类似的东西。

It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use getFile() - all though that would have been ideal if it was possible - as it's not necessarily an http:// prefix it could be c:/ or something similar.

推荐答案

new File(fileName).getName();

int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;

请注意,第一个解决方案是系统相关的。它只考虑系统的路径分隔符。因此,如果您的代码在Unix系统上运行并且接收Windows路径,那么它将无法工作。处理Internet Explorer发送的文件上载时就是这种情况。

Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.

这篇关于从Java中的文件位置获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆