Remove filename from a URL/Path in java
filepath, java, platform-independent, string
Solution
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
Problem
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