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.

share|improve this question
1  
YOU do realize there is no requirement for there to be a filename at the end, or even something that looks like a filename. In this case, there may or may not be a file.xml on server. – Miserable Variable Mar 3 '09 at 9:47
in that case, the result would be an empty string, or maybe null. – Sietse Mar 3 '09 at 9:57
I think you need to define the problem more clearly. What about following URLS endings? ..../abc, ..../abc/, ..../abc.def, ..../abc.def.ghi, ..../abc?def.ghi – Miserable Variable Mar 3 '09 at 10:10
I think it's pretty clear. If the URL points to a file, I'm interested in the filename minus the extension (if it has one). Query parts fall outside the filename. – Sietse Mar 3 '09 at 10:29
The client has no means of knowing if the server uses a file! – Miserable Variable Mar 3 '09 at 13:18
show 3 more comments

8 Answers

up vote 23 down vote accepted

This should about cut it (i'll leave the error handling to you):

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);
}
share|improve this answer
1  
One error handling aspect you need to consider is you will end up with an empty string if you accidentally pass it a url that doesnt have a filename (such as http://www.example.com/ or http://www.example.com/folder/) – rtpHarry Jan 21 '11 at 10:06
1  
The code doesn't work. lastIndexOf doesn't work this way. But the intention is clear. – Robert Dec 15 '11 at 1:58
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
share|improve this answer
Why the downvote? This is unfair. My code works, I just verified my code after seeing the downvote. – Real Red. Mar 3 '09 at 9:49
I upvoted you, because it's slightly more readable than my version. The downvote may be because it doesn't work when there's no extension or no file. – Sietse Mar 3 '09 at 9:59
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;
	}
share|improve this answer
Really Awesome! – SKR Jul 9 '12 at 7:33

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('.'));
share|improve this answer
Hmm this won't work on files without extensions. – Sietse Mar 3 '09 at 9:37
Or on URLs with no file, just a path. – Sietse Mar 3 '09 at 10:00
your code is correct too. we are not supposed to check for negative conditions anyway. an upvote for you. btw does the name dirk kuyt sound familiar? – Real Red. Mar 3 '09 at 10:06
good enough for simple cases – Dreen Dec 5 '12 at 15:54

Create an URL object from the String. When first you have an URL object there are methods to easily pull out just about any snippet of information you need.

I can strongly recommend the Javaalmanac web site which has tons of examples. You might find http://www.exampledepot.com/egs/java.io/File2Uri.html interesting.

share|improve this answer
The link you included is broken. – DavidA Dec 3 '12 at 21:31
Exampledepot appears to have gone missing – Thorbjørn Ravn Andersen Dec 27 '12 at 20:14

andy's answer redone using split():

Url u= ...;
String[] pathparts= u.getPath().split("\/");
String filename= pathparts[pathparts.length-1].split("\.", 1)[0];
share|improve this answer
public String getFileNameWithoutExtension(URL url) {
    String path = url.getPath();

    if (StringUtils.isBlank(path)) {
        return null;
    }
    if (StringUtils.endsWith(path, "/")) {
        //is a directory ..
        return null;
    }

    File file = new File(url.getPath());
    String fileNameWithExt = file.getName();

    int sepPosition = fileNameWithExt.lastIndexOf(".");
    String fileNameWithOutExt = null;
    if (sepPosition >= 0) {
        fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
    }else{
        fileNameWithOutExt = fileNameWithExt;
    }

    return fileNameWithOutExt;
}
share|improve this answer
import 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");

 }

I hope this will help you.

share|improve this answer
1  
getFile() doesn't do what you think. According to the doc it is actually getPath()+getQuery, which is rather pointless. java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html#getFile() – bobince Mar 3 '09 at 10:19

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.