【问题标题】:How to get the filename from all URLS JAVA [duplicate]如何从所有URLS JAVA中获取文件名[重复]
【发布时间】:2014-10-06 08:15:09
【问题描述】:

使用 JAVA 在 URL 中获取文件名的最佳方法是什么? 例如,如果我有https://www.example.com/notes/infortmation.html 我需要从 URL 中提取 information.html 部分(文件名)。我需要它适用于所有 URL。 (它们不会都是 html 文件)

【问题讨论】:

  • 并非所有 url 都有文件名。例如,https://www.example.com/
  • 您可以尝试使用URL#getFileURL#getPath,然后使用substring 获取最后一个/ 之后的内容...但老实说,您应该尝试一下...
  • 另外,您可以检查Content-Disposition 标头。

标签: java string parsing url


【解决方案1】:

如果我正确理解了这个问题,您有一个网址以及地址的最后一部分是什么。如果这是您的问题,您可以使用以下方法:

String add = "https://www.example.com/notes/infortmation.html"; 
String fileName = add.substring(add.lastIndexOf("/")+1) ;
System.out.println(fileName);

这将打印: 信息.html 但是,正如 cmets 中提到的,并非所有网址都有 filename.html 或 filename.php 等。请确保检查您正在解析的所有地址是否都具有此特征,否则上述方法将无法得到您想要的。

【讨论】:

    【解决方案2】:

    字符串文件名 = url.substring( url.lastIndexOf('/')+1, url.length() );

    注意这种网址https://www.example.com

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 2013-01-30
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2019-11-15
      • 2019-02-26
      • 1970-01-01
      相关资源
      最近更新 更多