Get file name from URL

2019-01-07 05:11发布

In Java, given a java.net.URL or a String in the form of http://www.example.com/some/path/to/a/file.xml , what is the easiest way to get the file name, minus the extension? So, in this example, I'm looking for something that returns "file".

I can think of several ways to do this, but I'm looking for something that's easy to read and short.

24条回答
三岁会撩人
2楼-- · 2019-01-07 05:29

Urls can have parameters in the end, this

 /**
 * Getting file name from url without extension
 * @param url string
 * @return file name
 */
public static String getFileName(String url) {
    String fileName;
    int slashIndex = url.lastIndexOf("/");
    int qIndex = url.lastIndexOf("?");
    if (qIndex > slashIndex) {//if has parameters
        fileName = url.substring(slashIndex + 1, qIndex);
    } else {
        fileName = url.substring(slashIndex + 1);
    }
    if (fileName.contains(".")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }

    return fileName;
}
查看更多
Deceive 欺骗
3楼-- · 2019-01-07 05:30
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
查看更多
闹够了就滚
4楼-- · 2019-01-07 05:30
String fileName = url.substring(url.lastIndexOf('/') + 1);
查看更多
Melony?
5楼-- · 2019-01-07 05:31

I've come up with this:

String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));
查看更多
Viruses.
6楼-- · 2019-01-07 05:31

There are some ways:

Java 7 File I/O:

String fileName = Paths.get(strUrl).getFileName().toString();

Apache Commons:

String fileName = FilenameUtils.getName(strUrl);

Using Jersey:

UriBuilder buildURI = UriBuilder.fromUri(strUrl);
URI uri = buildURI.build();
String fileName = Paths.get(uri.getPath()).getFileName();

Substring:

String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);
查看更多
冷血范
7楼-- · 2019-01-07 05:32
create a new file with string image path

    String imagePath;
    File test = new File(imagePath);
    test.getName();
    test.getPath();
    getExtension(test.getName());


    public static String getExtension(String uri) {
            if (uri == null) {
                return null;
            }

            int dot = uri.lastIndexOf(".");
            if (dot >= 0) {
                return uri.substring(dot);
            } else {
                // No extension.
                return "";
            }
        }
查看更多
登录 后发表回答