Java 如何获取uri的最后一个路径段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4050087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:57:26  来源:igfitidea点击:

How to obtain the last path segment of an uri

javastringurl

提问by DX89B

I have in input a string that is an URI. how is possible to get the last path segment? that in my case is an id?

我输入了一个字符串,它是一个URI. 怎么可能得到最后一个路径段?在我的情况下是一个id?

This is my input url

这是我的输入网址

String uri = "http://base_path/some_segment/id"

And I have to obtain the id I have tried with this

我必须获得我尝试过的 id

String strId = "http://base_path/some_segment/id";
strId=strId.replace(path);
strId=strId.replaceAll("/", "");
Integer id =  new Integer(strId);
return id.intValue();

but it doesn't work and for sure there is a better way to do it.

但它不起作用,并且肯定有更好的方法来做到这一点。

采纳答案by sfussenegger

is that what you are looking for:

这就是你要找的:

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);

alternatively

或者

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);

回答by Nageswara Rao

Get URL from URI and use getFile() if you are not ready to use substring way of extracting file.

如果您不准备使用子字符串方式提取文件,请从 URI 获取 URL 并使用 getFile()。

回答by Sean Patrick Floyd

Here's a short method to do it:

这是一个简短的方法:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\?.*)",");" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "");
}

Test Code:

测试代码:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}

Output:

输出:

42
foo
bar

42
FOO

Explanation:

解释:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above

回答by Colateral

import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();

回答by Jason C

I know this is old, but the solutions here seem rather verbose. Just an easily readable one-liner if you have a URLor URI:

我知道这很旧,但这里的解决方案似乎相当冗长。如果您有URL或 ,只是一个易于阅读的单行URI

String filename = new File(url.getPath()).getName();

Or if you have a String:

或者,如果您有String

String filename = new File(new URL(url).getPath()).getName();

回答by Will Humphreys

If you are using Java 8 and you want the last segment in a file path you can do.

如果您使用的是 Java 8 并且您想要文件路径中的最后一段,您可以这样做。

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();

If you have a url such as http://base_path/some_segment/idyou can do.

如果你有一个像http://base_path/some_segment/id你可以做的网址。

final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);

回答by Bnrdo

If you have commons-ioincluded in your project, you can do it without creating unecessary objects with org.apache.commons.io.FilenameUtils

如果你已经commons-io包含在你的项目中,你可以不用创建不必要的对象org.apache.commons.io.FilenameUtils

String uri = "http://base_path/some_segment/id";
String fileName = FilenameUtils.getName(uri);
System.out.println(fileName);

Will give you the last part of the path, which is the id

会给你路径的最后一部分,也就是 id

回答by jaco0646

In Java 7+ a few of the previous answers can be combined to allow retrieval of anypath segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Pathobject, to take advantage of its getName(int)method.

在 Java 7+ 中,可以将前面的一些答案组合起来,以允许从 URI 中检索任何路径段,而不仅仅是最后一个段。我们可以将 URI 转换为java.nio.file.Path对象,以利用其getName(int)方法。

Unfortunately, the static factory Paths.get(uri)is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.

不幸的是,静态工厂Paths.get(uri)不是为处理 http 方案而构建的,因此我们首先需要将方案与 URI 的路径分开。

URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();

To get the last segment in one line of code, simply nest the lines above.

要在一行代码中获得最后一段,只需嵌套上面的行。

Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()

Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()

To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent()method.

要获得倒数第二个段,同时避免索引号和潜在的一对一错误,请使用该getParent()方法。

String secondToLast = path.getParent().getFileName().toString();

String secondToLast = path.getParent().getFileName().toString();

Note the getParent()method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent()would retrieve the third-to-last segment.

请注意,getParent()可以重复调用该方法以按相反顺序检索段。在这个例子中,路径只包含两个段,否则调用getParent().getParent()将检索倒数第三个段。

回答by Sina Masnadi

You can use getPathSegments()function. (Android Documentation)

您可以使用getPathSegments()功能。(安卓文档

Consider your example URI:

考虑您的示例 URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

您可以使用以下方法获取最后一段:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegmentwill be id.

lastSegmentid

回答by Brill Pappin

In Android

在安卓中

Android has a built in class for managing URIs.

Android 有一个用于管理 URI 的内置类。

Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()