从 Java 中的 URL/路径中删除文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21829295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:57:09  来源:igfitidea点击:

Remove filename from a URL/Path in java

javastringfilepathplatform-independent

提问by Yemto

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

如何从 URL 或字符串中删除文件名?

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

这就是我现在所拥有的,并且有效。据我所知,因为我使用“/”,所以它只适用于 Windows。我想让它独立于平台

回答by Chthonic Project

Instead of "/", use File.separator. It is either /or \, depending on the platform. If this is not solving your issue, then use FileSystem.getSeparator(): you can pass different filesystems, instead of the default.

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

回答by Dirk Fauth

You are using File.separator in another line. Why not using it also for your lastIndexOf()?

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

nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));

回答by PopoFibo

Consider using org.apache.commons.io.FilenameUtils

考虑使用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";

带网址; String url = "C:/windows/system32/cmd.exe";

It would give;

它会给;

windows/system32/
cmd.exe

回答by Ksi?dz Pistolet

I solve this problem using regex.

我使用正则表达式解决了这个问题。

For windows:

对于窗户:

String path = "";
String filename = "d:\folder1\subfolder11\file.ext";
String regEx4Win = "\\(?=[^\\]+$)";
String[] tokens = filename.split(regEx4Win);
if (tokens.length > 0)
   path = tokens[0]; // path -> d:\folder1\subfolder11

回答by Jeremy Sigrist

The standard library can handle this as of Java 7

从 Java 7 开始,标准库就可以处理这个问题

Path pathOnly;

if (file.getNameCount() > 0) {
  pathOnly = file.subpath(0, file.getNameCount() - 1);
} else {
  pathOnly = file;
}

fileFunction.accept(pathOnly, file.getFileName());

回答by saygley

By utilizing java.nio.file; (afaik introduced after J2SE 1.7) this simply solved my problem:

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

Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();