当前位置:  开发笔记 > 编程语言 > 正文

从URL获取文件名

如何解决《从URL获取文件名》经验,为你挑选了11个好方法。

在Java中,给定a java.net.URL或a String形式http://www.example.com/some/path/to/a/file.xml,获取文件名的最简单方法是什么,减去扩展名?所以,在这个例子中,我正在寻找返回的东西"file".

我可以想到几种方法来做到这一点,但我正在寻找一些易于阅读和简短的方法.



1> Real Red...:
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));


为什么选择downvote?这不公平.我的代码有效,我只是在看到downvote后验证了我的代码.
这不适用于`http:// example.org/file#anchor`,`http://example.org/file?p = foo&q = bar`或`http://example.org/file. XML#/ p = FOO&q = bar`
如果URL具有参数,则无效
我赞成你,因为它比我的版本更具可读性.downvote可能是因为当没有扩展名或没有文件时它不起作用.
如果让`String url = new URL(original_url).getPath()`并为不包含`。'的文件名添加特殊情况,则可以正常工作。

2> Adrian B...:

如何使用Apache commons-io而不是重新发明轮子:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");

        System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
        System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
        System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
    }

}


FilenameUtils.getName(url)更适合.
FilenameUtils类设计用于Windows和*nix路径,而不是URL.
当简单的解决方案只使用JDK(参见`URL#getPath`和`String #substring`或`Path#getFileName`或`File#getName`)时,添加对commons-io的依赖似乎很奇怪.
更新了使用URL,显示示例输出值和使用查询参数的示例.
在版本commons-io 2.2中,至少你仍然需要手动处理带参数的URL.例如"http://example.com/file.xml?date=2010-10-20"
当它无法解决处理查询字符串的问题时,我看到这个解决方案随处可见.

3> tehvan..:

这应该削减它(我会留下错误处理给你):

int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
  filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
  filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}


代码不起作用.`lastIndexOf`不能这样工作.但目的很明确.

4> Zoltán..:

如果你不需要摆脱文件扩展名,那么这是一种方法,不需要使用容易出错的字符串操作而不使用外部库.适用于Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()



5> 小智..:
public static String getFileName(URL extUrl) {
        //URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
        String filename = "";
        //PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
        String path = extUrl.getPath();
        //Checks for both forward and/or backslash 
        //NOTE:**While backslashes are not supported in URL's 
        //most browsers will autoreplace them with forward slashes
        //So technically if you're parsing an html page you could run into 
        //a backslash , so i'm accounting for them here;
        String[] pathContents = path.split("[\\\\/]");
        if(pathContents != null){
            int pathContentsLength = pathContents.length;
            System.out.println("Path Contents Length: " + pathContentsLength);
            for (int i = 0; i < pathContents.length; i++) {
                System.out.println("Path " + i + ": " + pathContents[i]);
            }
            //lastPart: s659629384_752969_4472.jpg
            String lastPart = pathContents[pathContentsLength-1];
            String[] lastPartContents = lastPart.split("\\.");
            if(lastPartContents != null && lastPartContents.length > 1){
                int lastPartContentLength = lastPartContents.length;
                System.out.println("Last Part Length: " + lastPartContentLength);
                //filenames can contain . , so we assume everything before
                //the last . is the name, everything after the last . is the 
                //extension
                String name = "";
                for (int i = 0; i < lastPartContentLength; i++) {
                    System.out.println("Last Part " + i + ": "+ lastPartContents[i]);
                    if(i < (lastPartContents.length -1)){
                        name += lastPartContents[i] ;
                        if(i < (lastPartContentLength -2)){
                            name += ".";
                        }
                    }
                }
                String extension = lastPartContents[lastPartContentLength -1];
                filename = name + "." +extension;
                System.out.println("Name: " + name);
                System.out.println("Extension: " + extension);
                System.out.println("Filename: " + filename);
            }
        }
        return filename;
    }



6> Hiren Patel..:

获取带扩展名的文件,不带扩展名,使用3行扩展名:

String urlStr = "http://www.example.com/yourpath/foler/test.png";

String fileName = urlStr.substring(urlStr.lastIndexOf('/')+1, urlStr.length());
String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
String fileExtension = urlStr.substring(urlStr.lastIndexOf("."));

Log.i("File Name", fileName);
Log.i("File Name Without Extension", fileNameWithoutExtension);
Log.i("File Extension", fileExtension);

记录结果:

File Name(13656): test.png
File Name Without Extension(13656): test
File Extension(13656): .png

希望它会对你有所帮助.



7> Sietse..:

我想出来了:

String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));



8> juanmirocks..:

一个班轮:

new File(uri.getPath).getName

完整代码:

import java.io.File
import java.net.URI

val uri = new URI("http://example.org/file.txt?whatever")

new File(uri.getPath).getName
res18: String = file.txt

注意:URI#gePath已经足够智能去除查询参数和协议的方案.例子:

new URI("http://example.org/hey/file.txt?whatever").getPath
res20: String = /hey/file.txt

new URI("hdfs:///hey/file.txt").getPath
res21: String = /hey/file.txt

new URI("file:///hey/file.txt").getPath
res22: String = /hey/file.txt



9> Tim Autin..:

把事情简单化 :

/**
 * This function will take an URL as input and return the file name.
 * 

Examples :

*
    *
  • http://example.com/a/b/c/test.txt -> test.txt
  • *
  • http://example.com/ -> an empty string
  • *
  • http://example.com/test.txt?param=value -> test.txt
  • *
  • http://example.com/test.txt#anchor -> test.txt
  • *
* * @param url The input URL * @return The URL file name */ public static String getFileNameFromUrl(URL url) { String urlString = url.getFile(); return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0]; }



10> Yogesh Rathi..:
String fileName = url.substring(url.lastIndexOf('/') + 1);



11> Bharat Dodej..:

这是在Android中执行此操作的最简单方法.我知道它不适用于Java,但它可能有助于Android应用程序开发人员.

import android.webkit.URLUtil;

public String getFileNameFromURL(String url) {
    String fileNameWithExtension = null;
    String fileNameWithoutExtension = null;
    if (URLUtil.isValidUrl(url)) {
        fileNameWithExtension = URLUtil.guessFileName(url, null, null);
        if (fileNameWithExtension != null && !fileNameWithExtension.isEmpty()) {
            String[] f = fileNameWithExtension.split(".");
            if (f != null & f.length > 1) {
                fileNameWithoutExtension = f[0];
            }
        }
    }
    return fileNameWithoutExtension;
}

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有