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
The method fileCompinent() is used to remove the path information from a filename and return only its file component.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With