Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove filename from a URL/Path in java

How do I remove the file name from a URL or String?

String os = System.getProperty("os.name").toLowerCase();         String nativeDir = Game.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString();          //Remove the <name>.jar from the string         if(nativeDir.endsWith(".jar"))             nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf("/"));          //Load the right native files         for(File f : (new File(nativeDir + File.separator + "lib" + File.separator + "native")).listFiles()){             if(f.isDirectory() && os.contains(f.getName().toLowerCase())){                 System.setProperty("org.lwjgl.librarypath", f.getAbsolutePath()); break;             }         } 

That's what I have right now, and it work. From what I know, because I use "/" it will only work for windows. I want to make it platform independent

like image 695
Yemto Avatar asked Feb 17 '14 12:02

Yemto


People also ask

How to remove filename from path in Java?

The method fileCompinent() is used to remove the path information from a filename and return only its file component.

How do I get the filename from a URL?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.

How to work with path in Java?

Important methods of Path InterfacegetFileName() − Returns the file system that created this object. getName() − Returns a name element of this path as a Path object. getNameCount() − Returns the number of name elements in the path.


1 Answers

Consider using org.apache.commons.io.FilenameUtils

You can extract the base path, file name, extensions etc with any flavor of file separator:

String url = "C:\\windows\\system32\\cmd.exe";  String baseUrl = FilenameUtils.getPath(url); String myFile = FilenameUtils.getBaseName(url)                 + "." + FilenameUtils.getExtension(url);  System.out.println(baseUrl); System.out.println(myFile); 

Gives,

windows\system32\ cmd.exe 

With url; String url = "C:/windows/system32/cmd.exe";

It would give;

windows/system32/ cmd.exe 
like image 79
StoopidDonut Avatar answered Sep 22 '22 19:09

StoopidDonut