27

如何从 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;
            }
        }

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

4

9 回答 9

26

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

给,

windows\system32\
cmd.exe

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

它会给;

windows/system32/
cmd.exe
于 2014-02-17T13:13:39.257 回答
17

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

Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();
于 2018-01-05T14:21:20.270 回答
15

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

nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));
于 2014-02-17T12:45:10.427 回答
3

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

Path pathOnly;

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

fileFunction.accept(pathOnly, file.getFileName());
于 2017-03-14T03:27:26.037 回答
3
File file = new File(path);
String pathWithoutFileName = file.getParent();

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

于 2020-08-09T15:20:39.707 回答
1

Kotlin 解决方案:

val file = File( "/folder1/folder2/folder3/readme.txt")
val pathOnly = file.absolutePath.substringBeforeLast( File.separator )
println( pathOnly )

产生这个结果:

/文件夹1/文件夹2/文件夹3

于 2021-05-16T05:42:53.243 回答
0

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

于 2014-02-17T12:36:50.030 回答
0

请尝试以下代码:

file.getPath().replace(file.getName(), "");
于 2020-07-09T14:37:12.007 回答
0

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

对于窗户:

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
于 2017-03-03T11:10:24.423 回答