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 g
I have the same problem, with yours. I solved it by this:
var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1);
console.info(page)
There are some ways:
Java 7 File I/O:
String fileName = Paths.get(strUrl).getFileName().toString();
Apache Commons:
String fileName = FilenameUtils.getName(strUrl);
Using Jersey:
UriBuilder buildURI = UriBuilder.fromUri(strUrl);
URI uri = buildURI.build();
String fileName = Paths.get(uri.getPath()).getFileName();
Substring:
String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);
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, but which has since moved. You might find http://exampledepot.8waytrips.com/egs/java.io/File2Uri.html interesting:
// 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
}