views:

2630

answers:

7

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.

+2  A: 

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);
}
tehvan
+1  A: 

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('.'));
Sietse
Hmm this won't work on files without extensions.
Sietse
Or on URLs with no file, just a path.
Sietse
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?
Chandan .
+1  A: 
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
Chandan .
Why the downvote? This is unfair. My code works, I just verified my code after seeing the downvote.
Chandan .
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
A: 

Hi!!

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.

arpf
getFile() doesn't do what you think. According to the doc it is actually getPath()+getQuery, which is rather pointless. http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html#getFile()
bobince
A: 

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.

Thorbjørn Ravn Andersen
A: 

andy's answer redone using split():

Url u= ...;
String[] pathparts= u.getPath().split("\\/");
String filename= pathparts[pathparts.length-1].split("\\.", 1)[0];
bobince
+1  A: 
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;
 }
Mike