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");
}
// 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
}
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;
}
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 "";
}
}
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
注意 : URI#gePath已经足够智能,可以去掉查询参数和协议方案:
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