What is the best way of getting the file name in a URL using JAVA? For example if i have https://www.example.com/notes/infortmation.html I need to pull out information.html section (the file name) from the URL. I need this to work for all URLs. (they won't all be html files)
Asked
Active
Viewed 728 times
0
-
1Not all urls have filenames. For example, `https://www.example.com/`. – Elliott Frisch Aug 13 '14 at 04:45
-
1You could try using `URL#getFile` or `URL#getPath` and then use `substring` to get the content after the last `/`...but honestly, you should just try something... – MadProgrammer Aug 13 '14 at 04:46
-
Also, you might check for a [Content-Disposition](http://stackoverflow.com/questions/1012437/uses-of-content-disposition-in-an-http-response-header) header. – Elliott Frisch Aug 13 '14 at 04:48
2 Answers
0
If I understood the question correctly you have a web address and what the last part of the address. If that is the question you can do that using the following:
String add = "https://www.example.com/notes/infortmation.html";
String fileName = add.substring(add.lastIndexOf("/")+1) ;
System.out.println(fileName);
This will print: information.html However, as mentioned in the comments not all web addresses have a filename.html or filename.php, etc. Make sure to check if all the addresses that you are parsing have this characteristics otherwise the above method will not get you what you want.

AR5HAM
- 1,220
- 11
- 19
0
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
Be aware of this kind of urls https://www.example.com

naveejr
- 735
- 1
- 15
- 31