How to get parent URL in Java?

前端 未结 4 1255
眼角桃花
眼角桃花 2020-12-11 15:51

In Objective-C I use -[NSURL URLByDeletingLastPathComponent] to get parent URL. What\'s the equivalent of this in Java?

4条回答
  •  鱼传尺愫
    2020-12-11 16:21

    Here is very simple solution which was the best approach in my use case:

    private String getParent(String resourcePath) {
        int index = resourcePath.lastIndexOf('/');
        if (index > 0) {
            return resourcePath.substring(0, index);
        }
        return "/";
    }
    

    I created simple function, I was inspired by the code of File::getParent. In my code there is no issue with back slashes on Windows. I assume that resourcePath is resource part of URL, without protocol, domain and port number. (e.g. /articles/sport/atricle_nr_1234 )

提交回复
热议问题