简体   繁体   中英

Remove filename from a URL/Path in java

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

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

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

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

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

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

The standard library can handle this as of Java 7

Path pathOnly;

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

fileFunction.accept(pathOnly, file.getFileName());
File file = new File(path);
String pathWithoutFileName = file.getParent();

where path could be "C:\\Users\\userName\\Desktop\\file.txt"

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.

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

请尝试以下代码:

file.getPath().replace(file.getName(), "");

Kotlin solution:

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

produces this result:

/folder1/folder2/folder3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM