Java 从URL获取文件名

Java 从URL获取文件名,java,file,parsing,url,filenames,Java,File,Parsing,Url,Filenames,在Java中,给定一个Java.net.URL或一个String格式的http://www.example.com/some/path/to/a/file.xml,除去扩展名,获取文件名的最简单方法是什么?因此,在本例中,我正在寻找返回“file”的内容 我可以想出几种方法来做到这一点,但我正在寻找一种易于阅读和简短的方法。这应该可以减少它(我将把错误处理留给您): 我想到了这个: String url = "http://www.example.com/some/path/to/a/file.

在Java中,给定一个
Java.net.URL
或一个
String
格式的
http://www.example.com/some/path/to/a/file.xml
,除去扩展名,获取文件名的最简单方法是什么?因此,在本例中,我正在寻找返回
“file”
的内容

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

这应该可以减少它(我将把错误处理留给您):


我想到了这个:

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

import java.net.*;

public class ConvertURLToFileName{


   public static void main(String[] args)throws IOException{
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Please enter the URL : ");

   String str = in.readLine();


   try{

     URL url = new URL(str);

     System.out.println("File : "+ url.getFile());
     System.out.println("Converting process Successfully");

   }  
   catch (MalformedURLException me){

      System.out.println("Converting process error");

 }

我希望这对你有帮助

从字符串创建URL对象。当您第一次拥有URL对象时,有一些方法可以轻松地提取您需要的任何信息片段

我可以强烈推荐Javaalmanac网站,它有大量的例子,但后来它已经移动了。你可能会觉得有趣:

// Create a file object
File file = new File("filename");

// Convert the file object to a URL
URL url = null;
try {
    // The file need not exist. It is made into an absolute path
    // by prefixing the current working directory
    url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}

// Convert the URL to a file object
file = new File(url.getFile());  // d:/almanac1.4/java.io/filename

// Read the file contents using the URL
try {
    // Open an input stream
    InputStream is = url.openStream();

    // Read from is

    is.close();
} catch (IOException e) {
    // Could not open the file
}

使用split()重做andy的回答:

公共静态字符串getFileName(URL extUrl){
//URL:“http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
字符串filename=“”;
//路径:/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
String path=extUrl.getPath();
//检查前斜杠和/或反斜杠
//注意:**而URL中不支持反斜杠
//大多数浏览器都会用前斜杠自动替换它们
//所以从技术上讲,如果你在解析一个html页面,你可能会遇到
//一个反斜杠,所以我在这里解释它们;
String[]pathContents=path.split(“[\\/]”);
if(pathContents!=null){
int-pathContentsLength=pathContents.length;
System.out.println(“路径内容长度:+pathContentsLength”);
for(int i=0;i1){
int lastPartContentLength=lastPartContents.length;
System.out.println(“最后一部分长度:+lastPartContentLength”);
//文件名可以包含.,因此我们假设之前的所有内容
//最后一个。是名字,在最后一个之后的一切。是
//延伸
字符串名称=”;
for(int i=0;i
这个怎么样:

String filenameWithoutExtension = null;
String fullname = new File(
    new URI("http://www.xyz.com/some/deep/path/to/abc.png").getPath()).getName();

int lastIndexOfDot = fullname.lastIndexOf('.');
filenameWithoutExtension = fullname.substring(0, 
    lastIndexOfDot == -1 ? fullname.length() : lastIndexOfDot);

与其重新发明轮子,不如使用Apache:


下面是在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;
}

URL最后可以有参数,这

 /**
 * 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;
}

要返回不带扩展名的文件名和不带参数的,请使用以下命令:

String filenameWithParams = FilenameUtils.getBaseName(urlStr); // may hold params if http://example.com/a?param=yes
return filenameWithParams.split("\\?")[0]; // removing parameters from url if they exist
要返回扩展名不带参数的文件名,请使用以下命令:

/** Parses a URL and extracts the filename from it or returns an empty string (if filename is non existent in the url) <br/>
 * This method will work in win/unix formats, will work with mixed case of slashes (forward and backward) <br/>
 * This method will remove parameters after the extension
 *
 * @param urlStr original url string from which we will extract the filename
 * @return filename from the url if it exists, or an empty string in all other cases */
private String getFileNameFromUrl(String urlStr) {
    String baseName = FilenameUtils.getBaseName(urlStr);
    String extension = FilenameUtils.getExtension(urlStr);

    try {
        extension = extension.split("\\?")[0]; // removing parameters from url if they exist
        return baseName.isEmpty() ? "" : baseName + "." + extension;
    } catch (NullPointerException npe) {
        return "";
    }
}
/**解析URL并从中提取文件名或返回空字符串(如果URL中不存在文件名)
*此方法适用于win/unix格式,适用于斜杠的混合情况(向前和向后)
*此方法将在扩展后删除参数 * *@param urlStr原始url字符串,我们将从中提取文件名 *@从url返回文件名(如果存在),或在所有其他情况下返回空字符串*/ 私有字符串getFileNameFromUrl(字符串urlStr){ 字符串baseName=FilenameUtils.getBaseName(urlStr); 字符串扩展名=FilenameUtils.getExtension(urlStr); 试一试{ extension=extension.split(“\\?”[0];//从url中删除参数(如果存在) 返回baseName.isEmpty()?“”:baseName+“+扩展名; }捕获(NullPointerException npe){ 返回“”; } }
保持简单:

/**
 * This function will take an URL as input and return the file name.
 * <p>Examples :</p>
 * <ul>
 * <li>http://example.com/a/b/c/test.txt -> test.txt</li>
 * <li>http://example.com/ -> an empty string </li>
 * <li>http://example.com/test.txt?param=value -> test.txt</li>
 * <li>http://example.com/test.txt#anchor -> test.txt</li>
 * </ul>
 * 
 * @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];
}
/**
*此函数将以URL作为输入并返回文件名。
*示例:

*
    *
  • http://example.com/a/b/c/test.txt ->test.txt
  • *
  • http://example.com/ ->空字符串
  • *
  • http://example.com/test.txt?param=value ->test.txt
  • *
  • http://example.com/test.txt#anchor ->test.txt
  • *
* *@param url输入url *@返回URL文件名 */ 公共静态字符串getFileNameFromUrl(URL URL){ 字符串urlString=url.getFile(); 返回urlString.substring(urlString.lastIndexOf('/')+1.split(“\\?”)[0]。split(“\\”)[0]; }
获取扩展名为的文件名
不带扩展名仅扩展名,只有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
String fileName = Paths.get(strUrl).getFileName().toString();
String fileName = FilenameUtils.getName(strUrl);
UriBuilder buildURI = UriBuilder.fromUri(strUrl);
URI uri = buildURI.build();
String fileName = Paths.get(uri.getPath()).getFileName();
String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);

希望它能对您有所帮助。

如果您不需要删除文件扩展名,这里有一种方法可以做到这一点,而无需使用容易出错的字符串操作和外部库。适用于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()

如果只想从java.net.URL获取文件名(不包括任何查询参数),可以使用以下函数:

public static String getFilenameFromURL(URL url) {
    return new File(url.getPath().toString()).getName();
}
例如,此输入URL:

"http://example.com/image.png?version=2&amp;modificationDate=1449846324000"
将被转换为此输出字符串:
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()
String fileName = url.substring(url.lastIndexOf('/') + 1);
public static String getFilenameFromURL(URL url) {
    return new File(url.getPath().toString()).getName();
}
"http://example.com/image.png?version=2&amp;modificationDate=1449846324000"
image.png
System.out.println(FilenameUtils.getName("http://www.google.com/.."));
public static String getFilenameFromUrl(String url)
{
    if (url == null)
        return null;
    
    try
    {
        // Add a protocol if none found
        if (! url.contains("//"))
            url = "http://" + url;

        URL uri = new URL(url);
        String result = FilenameUtils.getName(uri.getPath());

        if (result == null || result.isEmpty())
            return null;

        if (result.contains(".."))
            return null;

        return result;
    }
    catch (MalformedURLException e)
    {
        return null;
    }
}
import java.util.Objects;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;

class Main {

  public static void main(String[] args) {
    validateFilename(null, null);
    validateFilename("", null);
    validateFilename("www.google.com/../me/you?trex=5#sdf", "you");
    validateFilename("www.google.com/../me/you?trex=5 is the num#sdf", "you");
    validateFilename("http://www.google.com/test.png?test", "test.png");
    validateFilename("http://www.google.com", null);
    validateFilename("http://www.google.com#test", null);
    validateFilename("http://www.google.com////", null);
    validateFilename("www.google.com/..", null);
    validateFilename("http://www.google.com/..", null);
    validateFilename("http://www.google.com/test", "test");
    validateFilename("https://www.google.com/../../test.png", "test.png");
    validateFilename("file://www.google.com/test.png", "test.png");
    validateFilename("file://www.google.com/../me/you?trex=5", "you");
    validateFilename("file://www.google.com/../me/you?trex", "you");
  }

  private static void validateFilename(String url, String expectedFilename){
    String actualFilename = getFilenameFromUrl(url);

    System.out.println("");
    System.out.println("url:" + url);
    System.out.println("filename:" + expectedFilename);

    if (! Objects.equals(actualFilename, expectedFilename))
      throw new RuntimeException("Problem, actual=" + actualFilename + " and expected=" + expectedFilename + " are not equal");
  }

  public static String getFilenameFromUrl(String url)
  {
    if (url == null)
      return null;

    try
    {
      // Add a protocol if none found
      if (! url.contains("//"))
        url = "http://" + url;

      URL uri = new URL(url);
      String result = FilenameUtils.getName(uri.getPath());

      if (result == null || result.isEmpty())
        return null;

      if (result.contains(".."))
        return null;

      return result;
    }
    catch (MalformedURLException e)
    {
      return null;
    }
  }
}
import java.util.ArrayList;
import java.util.StringTokenizer;

public class URLName {
    public static void main(String args[]){
        String url = "http://www.example.com/some/path/to/a/file.xml";
        StringTokenizer tokens = new StringTokenizer(url, "/");

        ArrayList<String> parts = new ArrayList<>();

        while(tokens.hasMoreTokens()){
            parts.add(tokens.nextToken());
        }
        String file = parts.get(parts.size() -1);
        int dot = file.indexOf(".");
        String fileName = file.substring(0, dot);
        System.out.println(fileName);
    }
}
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
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
String raw = "http://www.example.com/some/path/to/a/file.xml";
assertEquals("file.xml", Url.parse(raw).path().filename());

raw = "http://www.example.com/files/r%C3%A9sum%C3%A9.pdf";
assertEquals("résumé.pdf", Url.parse(raw).path().filename());
String fileName = Paths.get(strUrl).getFileName().toString();
String fileName = FilenameUtils.getName(strUrl);
UriBuilder buildURI = UriBuilder.fromUri(strUrl);
URI uri = buildURI.build();
String fileName = Paths.get(uri.getPath()).getFileName();
String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);
var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1); 
console.info(page)
List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);