从java中的URL/Path中删除文件名

Yem*_*mto 15 java string filepath platform-independent

如何从URL或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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

这就是我现在所拥有的,它的工作原理.据我所知,因为我使用"/"它只适用于Windows.我想让它与平台无关

Pop*_*ibo 19

考虑使用org.apache.commons.io.FilenameUtils

您可以使用任何文件分隔符提取基本路径,文件名,扩展名等:

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);
Run Code Online (Sandbox Code Playgroud)

给人,

windows\system32\
cmd.exe
Run Code Online (Sandbox Code Playgroud)

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

它会给;

windows/system32/
cmd.exe
Run Code Online (Sandbox Code Playgroud)


Dir*_*uth 10

您正在另一行使用File.separator.为什么不将它也用于你的lastIndexOf()?

nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));
Run Code Online (Sandbox Code Playgroud)


say*_*ley 9

通过利用java.nio.file ; (在J2SE 1.7之后引入afaik)这简单地解决了我的问题:

Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();
Run Code Online (Sandbox Code Playgroud)

  • 对于问题中没有特别提到的 HTTP URL 效果不佳,但某些浏览这些答案的人可能会感兴趣。 (2认同)

小智 9

File file = new File(path);
String pathWithoutFileName = file.getParent();
Run Code Online (Sandbox Code Playgroud)

其中路径可以是“C:\Users\userName\Desktop\file.txt”


Cht*_*ect 0

使用 代替“/” File.separator。它是 或/\具体取决于平台。如果这不能解决您的问题,请使用FileSystem.getSeparator():您可以传递不同的文件系统,而不是默认的文件系统。